The Python String isprintable() method is a built-in function that returns true if all the characters in a string are printable or if the string is empty. If not, it returns False.
In this article, we will learn about the Python String isprintable()
method with the help of examples.
What are printable characters in Python?
In Python, the character that occupies printing space on the screen is known as printable characters.
Examples of Printable characters are as follows –
- Alphabets
- Digits
- whitespace
- symbols and punctuation
isprintable() Syntax
The Syntax of isprintable()
method is:
string.isprintable()
isprintable() Parameters
The isprintable()
method does not take any parameters.
isprintable() Return Value
The isprintable()
method returns
True
if the string is empty or all the character in the string is printableFalse
if the string contains at least one non-printable character
Example 1: Working of isprintable() method
# valid text and printable
text = 'These are printable characters'
print(text)
print(text.isprintable())
# \n is not printable
text = '\nNew Line is printable'
print(text)
print(text.isprintable())
# \t is non printable
text = '\t tab is printable'
print(text)
print(text.isprintable())
# empty character is printable
text = ''
print('\nEmpty string printable?', text.isprintable())
Output
These are printable characters
True
New Line is printable
False
tab is printable
False
Empty string printable? True
Example 2: How to use isprintable() in real world?
In the below Program, we will iterate the given text to check and count how many non-printable characters are there. If we find any non-printable characters we will be replacing it with empty characters and finally we will be output the printable characters into ‘newtext’ variable which can print all the characters.
text = 'Welcome to ItsMyCode,\nPython\tProgramming\n'
newtext = ''
# Initialising the counter to 0
count = 0
# Iterate the text, count the non-printable characters
# replace non printable characters with empty string
for c in text:
if (c.isprintable()) == False:
count += 1
newtext += ' '
else:
newtext += c
print("Total Non Printable characters count is:", count)
print(newtext)
Output
Total Non Printable characters count is: 3
Welcome to ItsMyCode, Python Programming
from Planet Python
via read more
No comments:
Post a Comment