Most Pythonic was to strip all non-alphanumeric leading characters from string

我只是一个虾纸丫 提交于 2021-02-05 12:30:45

问题


For example

!@#123myname --> myname
!@#yourname!@#123 --> yourname!@#123

There are plenty of S.O. examples of "most pythonic ways of removing all alphanumeric characters" but if I want to remove only non-alphabet characters leading up to first alphabet character, what would be the best way to do this?

I can do it with a while loop but im looking for a better python solution


回答1:


If you want to remove leading non-alpha/numeric values:

while not s[0].isalnum(): s = s[1:]

If you want to remove only leading non-alphabet characters:

while not s[0].isalpha(): s = s[1:]

Sample:

s = '!@#yourname!@#'
while not s[0].isalpha(): s = s[1:]
print(s)

Output:

yourname!@#



回答2:


Just use str.lstrip.

It takes a string containing the characters to remove from the left side of the string, and will remove those characters regardless of the order in which they appear. For example:

s = "!@#yourname!@#"
print s.lstrip('@!#') # yourname!@#



回答3:


You could use a regex matching non-alphanumeric chars at the start of the string:

s = '!@#myname!!'
r = re.compile(r"^\W+") # \W non-alphanumeric at start ^ of string

Output:

In [28]: r = re.compile(r"^\W+")  
In [29]: r.sub("",'!@#myname')
Out[29]: 'myname'    
In [30]: r.sub("",'!@#yourname!@#')
Out[30]: 'yourname!@#'

\W+ will keep underscores so to just keep letters and digits at the start we can:

s = '!@#_myname!!'
r = re.compile(r"^[^A-Za-z0-9]+") 

print(r.sub("",s))
myname!!

If you want to just remove up to the first letter:

r = re.compile(r"^[^A-Za-z]+") 


来源:https://stackoverflow.com/questions/31033750/most-pythonic-was-to-strip-all-non-alphanumeric-leading-characters-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!