learn python string isprintable() with example

The isprintable() method is a built-in method in Python that belongs to the string class. It is used to determine whether all characters in a string are printable or not.

The isprintable() method returns True if all the characters in the string are printable, which means they can be displayed on the screen. If the string contains at least one non-printable character, the method returns False.



How to use the isprintable() method:

str1 = "Hello World!"
print(str1.isprintable()) # True

str2 = "Hello\nWorld!"
print(str2.isprintable()) # False

str3 = "12345"
print(str3.isprintable()) # True

str4 = "Hello\tWorld!"
print(str4.isprintable()) # False

Example 1

Conditional statement based on printable characters.

string = "Hello123"
if string.isprintable():
  print("The string is printable.")
  print("The string contains non-printable characters.")

Example 2

Removing non-printable characters from a string.

string = "He\tllo\nWor\rld!"
clean_string = ''.join(char for char in string if char.isprintable())
print(clean_string) # Output: HelloWorld!