测试 python 字符串是否可打印 [英] Test if a python string is printable
问题描述
我有一些代码可以从通信端口中提取数据,我想在打印之前确保我得到的确实是一个可打印的字符串(即 ASCII,可能是 UTF-8).有这样做的功能吗?我看了前六个地方,没有任何看起来像我想要的东西.(字符串可以打印 但我什么也没看到(那里,或在 字符串方法) 中检查一个字符串中的每个字符是否在另一个.
注意:控制字符不可出于我的目的而打印.
<小时>我正在/正在寻找一个单一的功能,而不是一个自己动手的解决方案:
我最终得到的是:
all(ord(c) <127 and c in string.printable for c in input_str)
正如你所说的 string
模块具有 printable
所以它只是检查字符串中的所有字符是否都在 printable
中:
您可以将两个字符串都转换为集合 - 因此该集合将包含字符串中的每个字符一次 - 并检查是否由您的字符串创建的集合 是可打印字符的子集:
<预><代码>>>>打印集 = 设置(字符串.可打印)>>>helloset = 设置(你好)>>>bellset = set(bell)>>>你好set(['!', ' ', 'e', 'd', 'H', 'l', 'o', 'r', 'W'])>>>helloset.issubset(打印集)真的>>>设置(贝尔). issubset(打印集)错误的所以,总而言之,您可能想要这样做:
导入字符串打印集 = 设置(字符串.可打印)isprintable = set(yourstring).issubset(printset)
I have some code that pulls data from a com-port and I want to make sure that what I got really is a printable string (i.e. ASCII, maybe UTF-8) before printing it. Is there a function for doing this? The first half dozen places I looked, didn't have anything that looks like what I want. (string has printable but I didn't see anything (there, or in the string methods) to check if every char in one string is in another.
Note: control characters are not printable for my purposes.
Edit: I was/am looking for a single function, not a roll-your-own solution:
What I ended up with is:
all(ord(c) < 127 and c in string.printable for c in input_str)
As you've said the string
module has printable
so it's just a case of checking if all the characters in your string are in printable
:
>>> hello = 'Hello World!'
>>> bell = chr(7)
>>> import string
>>> all(c in string.printable for c in hello)
True
>>> all(c in string.printable for c in bell)
False
You could convert both strings to sets - so the set would contain each character in the string once - and check if the set created by your string is a subset of the printable characters:
>>> printset = set(string.printable)
>>> helloset = set(hello)
>>> bellset = set(bell)
>>> helloset
set(['!', ' ', 'e', 'd', 'H', 'l', 'o', 'r', 'W'])
>>> helloset.issubset(printset)
True
>>> set(bell).issubset(printset)
False
So, in summary, you would probably want to do this:
import string
printset = set(string.printable)
isprintable = set(yourstring).issubset(printset)
这篇关于测试 python 字符串是否可打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!