Python remove anything that is not a letter or number

后端 未结 7 1277
甜味超标
甜味超标 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:26

    There are other ways also you may consider e.g. simply loop thru string and skip unwanted chars e.g. assuming you want to delete all ascii chars which are not letter or digits

    >>> newstring = [c for c in "a!1#b$2c%3\t\nx" if c in string.letters + string.digits]
    >>> "".join(newstring)
    'a1b2c3x'
    

    or use string.translate to map one char to other or delete some chars e.g.

    >>> todelete = [ chr(i) for i in range(256) if chr(i) not in string.letters + string.digits ]
    >>> todelete = "".join(todelete)
    >>> "a!1#b$2c%3\t\nx".translate(None, todelete)
    'a1b2c3x'
    

    this way you need to calculate todelete list once or todelete can be hard-coded once and use it everywhere you need to convert string

提交回复
热议问题