Stripping everything but alphanumeric chars from a string in Python

前端 未结 11 1424
不思量自难忘°
不思量自难忘° 2020-11-22 10:52

What is the best way to strip all non alphanumeric characters from a string, using Python?

The solutions presented in the PHP variant of this question will probably

11条回答
  •  温柔的废话
    2020-11-22 11:26

    How about:

    def ExtractAlphanumeric(InputString):
        from string import ascii_letters, digits
        return "".join([ch for ch in InputString if ch in (ascii_letters + digits)])
    

    This works by using list comprehension to produce a list of the characters in InputString if they are present in the combined ascii_letters and digits strings. It then joins the list together into a string.

提交回复
热议问题