Python String isprintable() 是用于字符串处理的 内置 方法。如果字符串中的所有字符都可打印或字符串为空,则 isprintable() 方法返回 “True”,否则返回 “False”。此函数用于检查参数是否包含任何可打印的字符,例如:
- 数字 (0123456789)
- 大写字母 ( ABCDEFGHIJKLMNOPQRSTUVWXYZ )
- 小写字母 ( abcdefghijklmnopqrstuvwxyz )
- 标点符号 ( !”#$%&'()*+, -./:;?@[\]^_`{ | }~ )
- 空间 ( )
用法:
string.isprintable()
参数:
isprintable() 不带任何参数
返回值:
- True - 如果字符串中的所有字符都可打印或字符串为空。
- False - 如果字符串包含 1 个或多个不可打印字符。
Errors Or Exceptions:
- 该函数不接受任何参数,因此不应传递任何参数,否则返回错误。
- 唯一可打印的空白字符是空格或“”,否则每个空白字符都是不可打印的,函数返回 “False”。
- 空字符串被认为是可打印的,它返回 “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())
输出:
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
相关用法
- Python String casefold()用法及代码示例
- Python String center()用法及代码示例
- Python String count()用法及代码示例
- Python String endswith()用法及代码示例
注:本文由纯净天空筛选整理自AyushSaxena大神的英文原创作品 Python String isprintable() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。