Categories
Python Answers

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

Spread the love

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.

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 *