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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。