Search code examples
pythonstringalphanumericnon-alphanumeric

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


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


Solution

  • 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!@#