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

前端 未结 3 838
[愿得一人]
[愿得一人] 2021-01-29 11:52

For example

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

There are plenty of S.O. examples of \"most pythonic ways of re

3条回答
  •  野性不改
    2021-01-29 12:26

    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]+") 
    

提交回复
热议问题