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

后端 未结 5 1390
故里飘歌
故里飘歌 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:35

    You can use a regex expression. The method re.sub() will take three parameters:

    • The regex expression
    • The replacement
    • The string

    Code:

    import re
    
    s = 'cats--'
    output = re.sub("[^\\w]", "", s)
    
    print output
    

    Explanation:

    • The part "\\w" matches any alphanumeric character.
    • [^x] will match any character that is not x

提交回复
热议问题