Python String isprintable() Method



The Python string isprintable() method is used to check whether all characters in a string are printable.

Printable characters are those that have a graphical representation and can be displayed on the screen. This includes digits, letters, punctuation marks, and whitespace characters, but excludes control characters such as newline (\n) and tab (\t).

Syntax

Following is the basic syntax of the Python String isprintable() method −

string.isprintable()

Parameter

This method does not accept any parameters.

Return Value

The method returns a boolean value "True" or "False". It returns True if all characters in the string are printable, and False otherwise.

Example

In the following example, we are checking if all characters in the string "text" are printable using the isprintable() method −

text = "Hello World"
result = text.isprintable()
print("The result is:",result)

Output

The output obtained is as follows −

The result is: True

Example

Here, we check if the characters in an empty string are printable using the isprintable() method −

text = ""
result = text.isprintable()
print("The result is:",result)     

Output

Since there are no characters in the string, the result obtained is True as shown below −

The result is: True

Example

In this example, we check if all the special characters such as "!", "@", "$" etc. in the string "text" are printable −

text = "!@#$%"
result = text.isprintable()
print("The result is:",result)   

Output

The result produced is as shown below −

The result is: True

Example

Now, we are checking if the string "text" containing newline character is printable or not using the isprintable() method −

text = "Hello\nWorld"
result = text.isprintable()
print("The result is:",result)  

Output

We get the output as shown below −

The result is: False

Example

This example checks whether all characters in the string "text" are printable. However, since the string contains ANSI escape codes for color formatting, which are control characters, it is considered not printable −

text = "\x1b[31mHello World\x1b[0m"
result = text.isprintable()
print("The result is:",result)  

Output

Following is the output of the above code −

The result is: False
boolean_string_methods.htm
Advertisements