Python String isprintable() 方法
Python String isprintable() 是用于字符串处理的内置方法。如果字符串中的所有字符都可打印或字符串为空,isprintable() 方法返回“True”,否则返回“False”。此函数用于检查参数是否包含任何可打印字符,例如:
- 数字 (0123456789)
- 大写字母 (ABCDEFGHIJKLMNOPQRSTUVWXYZ)
- 小写字母 (abcdefghijklmnopqrstuvwxyz)
- 标点符号( !”#$%&'()*+, -./:;?@[\]^_`{ | }~ )
- 空间 ( )
Syntax:
string.isprintable()
Parameters:
isprintable() does not take any parameters
Returns:
- True – If all characters in the string are printable or the string is empty.
- False – If the string contains 1 or more nonprintable characters.
Errors Or Exceptions:
- The function does not take any arguments, therefore no parameters should be passed, otherwise, it returns an error.
- The only whitespace character which is printable is space or ” “, otherwise every whitespace character is non-printable and the function returns “False”.
- The empty string is considered printable and it returns “True”.
示例 1
Input : string = 'My name is Ayush'
Output : True
Input : string = 'My name is \n Ayush'
Output : False
Input : string = ''
Output : True
Python3
# Python code for implementation of isprintable()
# checking for printable characters
string = 'My name is Ayush'
print(string.isprintable())
# checking if \n is a printable character
string = 'My name is \n Ayush'
print(string.isprintable())
# checking if space is a printable character
string = ''
print( string.isprintable())
Python3
# Python implementation to count
# non-printable characters in a string
# Given string and new string
string ='GeeksforGeeks\nname\nis\nCS portal'
newstring = ''
# Initialising the counter to 0
count = 0
# Iterating the string and
# checking for non-printable characters
# Incrementing the counter if a
# non-printable character is found
# and replacing it by space in the newstring
# Finally printing the count and newstring
for a in string:
if (a.isprintable()) == False:
count+= 1
newstring+=' '
else:
newstring+= a
print(count)
print(newstring)
输出:
True
False
True
示例 2:实际应用
给定Python中的字符串,计算字符串中不可打印字符的数量,并用空格替换不可打印字符。
Input : string = 'My name is Ayush'
Output : 0
My name is Ayush
Input : string = 'My\nname\nis\nAyush'
Output : 3
My name is Ayush
算法:
- 初始化一个空的新字符串和一个变量 count = 0。
- 一个字符一个字符地遍历给定的字符串直到它的长度,检查这个字符是否是一个不可打印的字符。
- 如果它是不可打印的字符,则将计数器加 1,并在新字符串中添加一个空格。
- 否则,如果它是可打印字符,则将其按原样添加到新字符串中。
- 打印计数器的值和新字符串。
Python3
# Python implementation to count
# non-printable characters in a string
# Given string and new string
string ='GeeksforGeeks\nname\nis\nCS portal'
newstring = ''
# Initialising the counter to 0
count = 0
# Iterating the string and
# checking for non-printable characters
# Incrementing the counter if a
# non-printable character is found
# and replacing it by space in the newstring
# Finally printing the count and newstring
for a in string:
if (a.isprintable()) == False:
count+= 1
newstring+=' '
else:
newstring+= a
print(count)
print(newstring)
输出:
3
GeeksforGeeks name is CS portal