How to rermove non-alphanumeric characters at the beginning or end of a string

后端 未结 5 1393
故里飘歌
故里飘歌 2020-12-07 03:27

I have a list with elements that have unnecessary (non-alphanumeric) characters at the beginning or end of each string.

Ex.

\'cats--\'
5条回答
  •  日久生厌
    2020-12-07 03:51

    To remove one or more chars other than letters, digits and _ from both ends you may use

    re.sub(r'^\W+|\W+$', '', '??cats--') # => cats
    

    Or, if _ is to be removed, too, wrap \W into a character class and add _ there:

    re.sub(r'^[\W_]+|[\W_]+$', '', '_??cats--_')
    

    See the regex demo and the regex graph:

    See the Python demo:

    import re
    print( re.sub(r'^\W+|\W+$', '', '??cats--') )          # => cats
    print( re.sub(r'^[\W_]+|[\W_]+$', '', '_??cats--_') )  # => cats
    

提交回复
热议问题