Search code examples
pythonregexstringprefixsuffix

How to cut non-alphanumeric prefix and suffix from a string in Python?


How to cut all characters from the beginning and the end of the string which are not alphanumerical?

For example:

print(clearText('%!_./123apple_42.juice_(./$)'))
# => '123apple_42.juice'

print(clearText('  %!_also remove.white_spaces(./$)   '))
# => 'also remove.white_spaces'

Solution

  • This guy grabs everything between alphanumeric characters.

    import re
    
    def clearText(s):
        return re.search("[a-zA-Z0-9].*[a-zA-Z0-9]", s).group(0)
    
    print(clearText("%!_./123apple_42.juice_(./$)"))