pythonregexstrip

How to strip non-letter characters from beginning and end of a string in Python?


I need to remove all non-letter characters from the beginning and from the end of a word, but keep them if they appear between two letters.

For example:

'123foo456' --> 'foo'
'2foo1c#BAR' --> 'foo1c#BAR'

I tried using re.sub(), but I couldn't write the regex.


Solution

  • like this?

    re.sub('^[^a-zA-Z]*|[^a-zA-Z]*$','',s)
    

    s is the input string.