Sometimes, we want to replace non-ASCII characters with a single space with Python.
In this article, we’ll look at how to replace non-ASCII characters with a single space with Python.
How to replace non-ASCII characters with a single space with Python?
To replace non-ASCII characters with a single space with Python, we can use string’s join
method with list comprehension.
For instance, we write
''.join([i if ord(i) < 128 else ' ' for i in text])
to replace all non-ASCII characters with spaces with
i if ord(i) < 128 else ' '
Is the character code is less than 128 as returned by ord
then the character is an ASCII character.
i
is the character being iterated through in the text
string.
We put the converted characters in a list and then call join
on the list to join the list back into a string.
Conclusion
To replace non-ASCII characters with a single space with Python, we can use string’s join
method with list comprehension.