2016-10-07 10 views
0

randomString.decode( "utf-8")とstr(randomString、 "utf-8")の違いは何ですか?
私は彼らが同じことを見るが、私がそれらを試してみると、彼らは異なっていることが分かる!randomString.decode( "utf-8")とstr(randomString、 "utf-8")の違いは何ですか?

>>> randomString = "Hello World"
>>> str(randomString)
\'Hello World'
>>> randomString.decode("utf-8")
Traceback (most recent call last):
File "< input >", line 1, in
AttributeError: 'str' object has no attribute 'decode'
>>> randomString.encode()
b'Hello World'
>>> bString = randomString.encode()
>>> bString.decode()
'Hello World'
>>> str(bString)
"b'Hello World'"


と私は本当に、通常の文字列とバイト列の違いを理解していませんか? ヘルプplz!

+0

'randomString = "Hello Worldのをěščřž" お試しください。 print(randomString.encode( "utf-8")) 'で非ASCII文字の一部を使用します。注** encode **は文字列からバイトへの変換で、** decode **は文字列からバイトへの変換です。 – JosefZ

+0

私がBytes:__b'Hello World \ xc4 \ x9b \ xc5 \ xa1 \ xc4 \ x8d \ xc5 \ x99 \ xc5 \ xbe '__ ,,を与えてもokですが、私はデコード部分と混乱しています... str (randomBytes、 "utf-8")はrandomBytes.decode( "utf-8")のようにデコードしますか? –

+0

'print(str(randomString.encode()、" utf-8 ")== randomString.encode()。decode())'返す**本当の**だからあなたは何を求めていますか? – JosefZ

答えて

0

読む(Python) Built-in Functionsstr() in detail

class str(object='') 
class str(object=b'', encoding='utf-8', errors='strict') 

Return a string version of object. If object is not provided, returns the empty string. Otherwise, the behavior of str() depends on whether encoding or errors is given, as follows.

If neither encoding nor errors is given, str(object) returns object.__str__() , which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a __str__() method, then str() falls back to returning repr(object) .

If at least one of encoding or errors is given, object should be a bytes-like object (e.g. bytes or bytearray). In this case, if object is a bytes (or bytearray) object, then str(bytes, encoding, errors) is equivalent tobytes.decode(encoding, errors) . Otherwise, the bytes object underlying the buffer object is obtained before calling bytes.decode() . See Binary Sequence Types — bytes, bytearray, memoryview and Buffer Protocol for information on buffer objects.

上記引用文で明示的にすべてのリンクが与えられていないことに注意してください。

(Pythonの3.5.1):

>>> 
>>> randomString = 'latin, ελληνικά, кириллица' 
>>> 
>>> print (str(randomString.encode(),"utf-8") == randomString.encode().decode()) 
True 
>>> 
関連する問題