Sometimes, we want to strip everything but alphanumeric chars from a string in Python.
In this article, we’ll look at how to strip everything but alphanumeric chars from a string in Python.
How to strip everything but alphanumeric chars from a string in Python?
To strip everything but alphanumeric chars from a string in Python, we can split the string and then use the isalnum method to filter out non alphanumeric characters.
For instance, we write
s = ''.join(ch for ch in some_string if ch.isalnum())
to filter out all the non-alphanumeric characters with
ch for ch in some_string if ch.isalnum()
isalnum is a string method to check if a string has all alphanumeric characters.
Then we call join to join the filtered substrings together.
Conclusion
To strip everything but alphanumeric chars from a string in Python, we can split the string and then use the isalnum method to filter out non alphanumeric characters.