Python字符串isprintable()

Python String isprintable() function returns True if all characters in the string are printable or the string is empty, False otherwise.

如果字符串中的所有字符均可打印或字符串为空,则Python String isprintable()函数将返回True否则返回False

Python字符串isprintable() (Python String isprintable())

Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, except the ASCII space (0x20) which is considered printable.

不可打印字符是在Unicode字符数据库中定义为“其他”或“分隔符”的那些字符,但认为可打印的ASCII空间(0x20)除外。

Note that printable characters in this context are those which should not be escaped when repr() is invoked on a string.

请注意,在此上下文中,可打印字符是在字符串上调用repr()时不应转义的那些字符。

Let’s look at some examples of Python String isprintable() function.

让我们来看一些Python String isprintable()函数的示例。

s = 'Hi Hello World'

print(s.isprintable())

Output: True because all the characters are printable and space is considered as a printable character.

输出: True因为所有字符都是可打印的,并且空格被视为可打印的字符。

s = ''
print(s.isprintable())

Output: True because empty string is considered as printable.

输出: True因为空字符串被认为是可打印的。

s = 'Hi\tHello'
print(s.isprintable())

Output: False because \t is not a printable character.

输出: False因为\ t不是可打印字符。

s = 'Hi\nHello'
print(s.isprintable())

Output: False because \n is not a printable character.

输出: False因为\ n不是可打印字符。

s = 'Hi\'Hello'
print(s.isprintable())
print(s)

Output:

输出:

True
Hi'Hello

Let’s look at another example with some escape characters.

让我们看另一个带有转义字符的示例。

s = 'Hi\bHello'
print(s.isprintable())
print(s)

Output:

输出:

False
HHello

The \b character is considered as non-printable.

\ b字符被认为是不可打印的。

s = 'Hi\aHello'
print(s.isprintable())
print(s)

Output:

输出:

False
HiHello

The \a character is considered as non-printable.

\ a字符被视为不可打印。

s = 'Hi\u0066Hello'
print(s.isprintable())
print(s)

s = 'Hi\u0009Hello'
print(s.isprintable())
print(s)

Output:

输出:

True
HifHello
False
Hi	Hello

The \u0066 (f) is printable whereas \u0009 (\t) is non-printable.

\ u0066(f)是可打印的,而\ u0009(\ t)是不可打印的。

打印所有非打印字符列表 (Print all Non-Printable Characters List)

Here is a simple code snippet to print the list of non-printable characters details.

这是一个简单的代码段,用于打印不可打印字符的详细信息列表。

count = 0
for codepoint in range(2 ** 16):
    ch = chr(codepoint)
    if not ch.isprintable():
        print(u'{:04x}'.format(codepoint))
        count = count + 1
print(f'Total Number of Non-Printable Unicode Characters = {count}')

Output:

输出:

0000
0001
0002
...
fffb
fffe
ffff
Total Number of Non-Printable Unicode Characters = 10249
GitHub Repository. GitHub存储库中签出更多Python示例。

Reference: Official Documentation

参考: 官方文档

翻译自: https://www.journaldev.com/24137/python-string-isprintable

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值