Python字符串isprintable()是用于字符串处理的内置方法。如果字符串中的所有字符都可打印或字符串为空,isprintable()方法返回“True”,否则返回“False”。此函数用于检查参数是否包含任何可打印字符,例如:
null
- 数字(0123456789)
- 大写字母(abcdefghijklmnopqrstuvxyz)
- 小写字母(abcdefghijklmnopqrstuvwxyz)
- 标点符号(!“#$%&’()*+,-./:@[]^_`{ | }~ )
- 空格()
语法:
一串可打印()
参数:
isprintable()不接受任何参数
返回:
- True–如果字符串中的所有字符都可打印或字符串为空。
- False–如果字符串包含1个或多个不可打印字符。
错误或例外:
- 该函数不接受任何参数,因此不应传递任何参数,否则将返回错误。
- 唯一可打印的空白字符是 空间 或“”,否则每个空白字符都不可打印,函数返回“False”。
- 空字符串被认为是可打印的,并返回“True”。
例1
Input : string = 'My name is Ayush' Output : True Input : string = 'My name is 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 is a printable character string = 'My name is 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 = 'MynameisAyush' 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 = 'GeeksforGeeksnameisCS 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
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END