Use the isprintable()
method to check if the characters in a string are printable.
text = '' # notice this is an empty string, there is no white space here
print(text.isprintable())
#output: True
text = 'This is a regular text'
print(text.isprintable())
#output: True
text = ' ' #one space
print(text.isprintable())
#output: True
text = ' ' #many spaces
print(text.isprintable())
#output: True
text = '\f\n\r\t\v'
print(text.isprintable())
#output: False
Notice that in the first 4 examples, all the character take some space, even if it is an empty space as you could see in the first example.
The last example returns False
, showing 5 kind of characters that are non-printable: form feed \f
, line feed \n
, carriage return \r
, tab \t
, and vertical tab \v
.
Some of these ‘invisible’ characters may mess up your printing giving you an unxpected output, even when everything ‘looks’ alright.