Python 字符串 isprintable() 方法用于检查字符串中的所有字符是否都是可打印的。
可打印字符是具有图形表示并且可以在屏幕上显示的字符。这包括数字、字母、标点符号和空白字符,但不包括换行符 (\n) 和制表符 (\t) 等控制字符。
语法
以下是 Python String isprintable() 方法的基本语法 -
string.isprintable()
参数
此方法不接受任何参数。
返回值
该方法返回布尔值 “True” 或 “False”。如果字符串中的所有字符都是可打印的,则返回 True,否则返回 False。
例在下面的示例中,我们使用 isprintable() 方法检查字符串 “text” 中的所有字符是否都可打印 -
text = "Hello World"
result = text.isprintable()
print("The result is:",result)
输出
获得的输出如下 -
The result is: True
例
在这里,我们使用 isprintable() 方法检查空字符串中的字符是否可打印 -
text = ""
result = text.isprintable()
print("The result is:",result)
输出
由于字符串中没有字符,因此获得的结果是 True,如下所示 -
The result is: True
例
在这个例子中,我们检查字符串 “text” 中的所有特殊字符,如 “!”、“@”、“$” 等是否都是可打印的 -
text = "!@#$%"
result = text.isprintable()
print("The result is:",result)
输出
生成的结果如下所示 -
The result is: True
例
现在,我们正在使用 isprintable() 方法检查包含换行符的字符串 “text” 是否可打印 -
text = "Hello\nWorld"
result = text.isprintable()
print("The result is:",result)
输出
我们得到的输出如下所示 -
The result is: False
例
此示例检查字符串 “text” 中的所有字符是否都可打印。但是,由于字符串包含用于颜色格式的 ANSI 转义码,这些转义码是控制字符,因此被视为不可打印 -
text = "\x1b[31mHello World\x1b[0m"
result = text.isprintable()
print("The result is:",result)
输出
以下是上述代码的输出 -
The result is: False