Python 字符串 isprintable()

isprintable() 方法返回 True,如果 字符串 中的所有字符都是可打印的。否则,它返回 False

示例

text = 'apple'

# returns True if text is printable result = text.isprintable()
print(result) # Output: True

isprintable() 语法

isprintable() 方法的语法是

string.isprintable()

这里,isprintable() 检查 string 是否可打印。

注意

  • 在屏幕上占据打印空间的字符被称为可打印字符。例如,字母、符号、数字、标点符号、空格。
  • 不占据空间且用于格式化的字符被称为不可打印字符。例如,换行符、分页符。

isprintable() 参数

isprintable() 方法不接受任何参数。


isprintable() 返回值

isprintable() 方法返回

  • True - 如果字符串中的所有字符都是可打印的
  • False - 如果字符串中包含至少一个不可打印字符

示例 1:Python 字符串 isprintable()

text1 = 'python programming'

# checks if text1 is printable result1 = text1.isprintable()
print(result1) text2 = 'python programming\n'
# checks if text2 is printable result2 = text2.isprintable()
print(result2)

输出

True
False

在上面的例子中,我们使用 isprintable() 方法检查 text1text2 字符串是否可打印。

这里,

  • text1.isprintable() - 返回 True,因为 'python programming' 是可打印字符串
  • text2.isprintable() - 返回 False,因为 'python programming\n' 包含一个不可打印字符 '\n'

这意味着如果我们打印 text2,它不会打印 '\n' 字符,

print(text2)
# Output: python programing

示例 2:isprintable() 与空字符串

当我们传入空字符串时,isprintable() 方法返回 True。例如,

empty_string = ' '

# returns True with an empty string print(empty_string.isprintable())

输出

True

这里,empty_string.isprintable() 返回 True


示例 3:isprintable() 与包含 ASCII 的字符串

# defining string using ASCII value 
text = chr(27) + chr(97)

# checks if text is printable if text.isprintable():
print('Printable') else: print('Not Printable')

输出

Not Printable

在上面的例子中,我们使用 ASCII 定义了 text 字符串。这里,

  • chr(27) - 是转义字符,即反斜杠 \
  • chr(97) - 是字母'a'

text.isprintable() 代码返回 False,因为 chr(27) + chr(97) 包含不可打印的转义字符。

因此程序执行 else 部分。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战