📜  Python String isprintable() 方法

📅  最后修改于: 2022-05-13 01:55:14.332000             🧑  作者: Mango

Python String isprintable() 方法

Python String isprintable() 是用于字符串处理的内置方法。如果字符串中的所有字符都可打印或字符串为空,isprintable() 方法返回“True”,否则返回“False”。此函数用于检查参数是否包含任何可打印字符,例如:

  • 数字 (0123456789)
  • 大写字母 (ABCDEFGHIJKLMNOPQRSTUVWXYZ)
  • 小写字母 (abcdefghijklmnopqrstuvwxyz)
  • 标点符号( !”#$%&'()*+, -./:;?@[\]^_`{ | }~ )
  • 空间 ( )

示例 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

算法:

  1. 初始化一个空的新字符串和一个变量 count = 0。
  2. 一个字符一个字符地遍历给定的字符串直到它的长度,检查这个字符是否是一个不可打印的字符。
  3. 如果它是不可打印的字符,则将计数器加 1,并在新字符串中添加一个空格。
  4. 否则,如果它是可打印字符,则将其按原样添加到新字符串中。
  5. 打印计数器的值和新字符串。

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