Gre*_*ill 276
在Python 3中,所有字符串都是Unicode字符序列.有一种bytes
类型可以保存原始字节.
在Python 2中,字符串可以是类型str
或类型unicode
.你可以告诉使用这样的代码:
def whatisthis(s):
if isinstance(s, str):
print "ordinary string"
elif isinstance(s, unicode):
print "unicode string"
else:
print "not a string"
Run Code Online (Sandbox Code Playgroud)
这不区分"Unicode或ASCII"; 它只区分Python类型.Unicode字符串可以由ASCII范围内的纯字符组成,字节字符串可以包含ASCII,编码的Unicode或甚至非文本数据.
Mik*_*kel 116
做就是了
>>> type(u'abc') # Python 2 unicode string literal
<type 'unicode'>
>>> type('abc') # Python 2 byte string literal
<type 'str'>
Run Code Online (Sandbox Code Playgroud)
有人会说type
,对方会说isinstance
.
您可以使用str
例如单独处理它们
>>> type('abc') # Python 3 unicode string literal
<class 'str'>
>>> type(b'abc') # Python 3 byte string literal
<class 'bytes'>
Run Code Online (Sandbox Code Playgroud)
或者你的意思是你有一个unicode
,并且你试图弄清楚它是用str
或unicode
其他东西编码的?
在这种情况下,试试这个:
>>> u_umlaut = b'\xc3\x9c' # UTF-8 representation of the letter 'Ü'
>>> u_umlaut.decode('utf-8')
u'\xdc'
>>> u_umlaut.decode('ascii')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
如果它引发异常,则该字符串不是100%ASCII.
Thi*_*obo 44
在python 3.x中,所有字符串都是Unicode字符序列.并且执行str的isinstance检查(默认情况下意味着unicode字符串)就足够了.
isinstance(x, str)
Run Code Online (Sandbox Code Playgroud)
关于python 2.x,大多数人似乎都在使用带有两个检查的if语句.一个用于str,一个用于unicode.
如果你想检查你是否有一个'字符串'对象都有一个语句,你可以执行以下操作:
isinstance(x, basestring)
Run Code Online (Sandbox Code Playgroud)
Ale*_*ean 31
Unicode不是一种编码 - 引用Kumar McMillan:
如果ASCII,UTF-8和其他字节字符串是"文本"...
......然后Unicode就是"文本";
它是文本的抽象形式
阅读了McMillan的Python In Python,来自PyCon 2008的完全神秘化的演讲,它解释了比Stack Overflow上大多数相关答案好得多的东西.
Dav*_*ton 23
如果你的代码需要兼容两者的Python 2和Python 3,你不能直接使用之类的东西isinstance(s,bytes)
或isinstance(s,unicode)
不带/包裹它们可尝试不同的或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)
Run Code Online (Sandbox Code Playgroud)
一个可以说是稍微不那么丑陋的解决方法是检查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)
Run Code Online (Sandbox Code Playgroud)
这些都是unpythonic,大多数时候可能有更好的方式.
mad*_*rdi 11
使用:
import six
if isinstance(obj, six.text_type)
Run Code Online (Sandbox Code Playgroud)
在六个库中它代表:
if PY3:
string_types = str,
else:
string_types = basestring,
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
312585 次 |
最近记录: |