Categories
Python Answers

How to replace non-ASCII characters with a single space with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *