Menu Close

How to strip non printable characters from a string in Python?

Sometimes, we want to strip non printable characters from a string in Python.

In this article, we’ll look at how to strip non printable characters from a string in Python.

How to strip non printable characters from a string in Python?

To strip non printable characters from a string in Python, we can call the isprintable method on each character and use list comprehension.

For instance, we write

s = ''.join(c for c in my_string if c.isprintable())

to check if each character in my_string is printable with isprintable.

And we return an iterator with all the printable characters with

c for c in my_string if c.isprintable()

Then we call ''.join with the iterator to join the printable characters in my_string back to a string.

Conclusion

To strip non printable characters from a string in Python, we can call the isprintable method on each character and use list comprehension.

Posted in Python, Python Answers