Python remove anything that is not a letter or number

后端 未结 7 1281
甜味超标
甜味超标 2020-12-24 01:40

I\'m having a little trouble with Python regular expressions.

What is a good way to remove all characters in a string that are not letters or numbers?

Thanks

7条回答
  •  春和景丽
    2020-12-24 02:14

    In the char set matching rule [...] you can specify ^ as first char to mean "not in"

    import re
    re.sub("[^0-9a-zA-Z]",        # Anything except 0..9, a..z and A..Z
           "",                    # replaced with nothing
           "this is a test!!")    # in this string
    
    --> 'thisisatest'
    

提交回复
热议问题