我必须在Python中做什么来找出字符串的编码?
当前回答
在Python-3中,我必须理解字符串是否像b='\x7f\x00\x00\x01'或b='127.0.0.1'我的解决方案是这样的:
def get_str(value):
str_value = str(value)
if str_value.isprintable():
return str_value
return '.'.join(['%d' % x for x in value])
对我有用,我希望对有需要的人有用
其他回答
在Python-3中,我必须理解字符串是否像b='\x7f\x00\x00\x01'或b='127.0.0.1'我的解决方案是这样的:
def get_str(value):
str_value = str(value)
if str_value.isprintable():
return str_value
return '.'.join(['%d' % x for x in value])
对我有用,我希望对有需要的人有用
如果你的代码需要与Python 2和Python 3兼容,你不能直接使用isinstance(s,bytes)或isinstance(s,unicode)这样的东西,而不将它们包装在try/except或Python版本测试中,因为bytes在Python 2中未定义,unicode在Python 3中未定义。
有一些丑陋的变通办法。一种非常糟糕的方法是比较类型的名称,而不是比较类型本身。这里有一个例子:
# convert bytes (python 3) or unicode (python 2) to str
if str(type(s)) == "<class 'bytes'>":
# only possible in Python 3
s = s.decode('ascii') # or s = str(s)[2:-1]
elif str(type(s)) == "<type 'unicode'>":
# only possible in Python 2
s = str(s)
一个稍微不那么丑陋的解决方法是检查Python版本号,例如:
if sys.version_info >= (3,0,0):
# for Python 3
if isinstance(s, bytes):
s = s.decode('ascii') # or s = str(s)[2:-1]
else:
# for Python 2
if isinstance(s, unicode):
s = str(s)
这两个都是非python的,大多数时候可能有更好的方法。
一种简单的方法是检查unicode是否是内置函数。如果是,你在python2中,你的字符串将是一个字符串。要确保所有内容都使用unicode,可以执行以下操作:
import builtins
i = 'cats'
if 'unicode' in dir(builtins): # True in python 2, False in 3
i = unicode(i)
在python3中,所有字符串都是Unicode字符的序列。有一种bytes类型保存原始字节。
在python2中,字符串的类型可以是str或unicode。你可以用如下代码来区分:
def whatisthis(s):
if isinstance(s, str):
print "ordinary string"
elif isinstance(s, unicode):
print "unicode string"
else:
print "not a string"
这并不区分“Unicode或ASCII”;它只区分Python类型。Unicode字符串可以由ASCII范围内的纯字符组成,字节字符串可以包含ASCII、编码的Unicode,甚至是非文本数据。
在python中3。x所有字符串都是Unicode字符的序列。使用isinstance检查STR(默认为unicode字符串)就足够了。
isinstance(x, str)
关于python 2.x, 大多数人似乎都在使用带有两次检查的if语句。一个用于STR,一个用于unicode。
如果你想检查你是否有一个'string-like'的对象,并且只有一个语句,你可以这样做:
isinstance(x, basestring)
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录