2016-09-29 46 views
6

在Python 3,如果我有一個字符串這樣的:如何識別字符串爲字節文字?

print(some_str) 

得到這樣的事情:

b'This is the content of my string.\r\n' 

我知道它的字面一個字節。

是否有一個函數可以用來確定該字符串是否採用字節字面格式(相對於Unicode 'u'前綴)而無需第一次解釋?或者還有另一個處理這個問題的最佳做法?我有一種情況,其中獲取字節字符串需要以不同於Unicode的方式處理。從理論上講,這樣的事情:

if is_byte_literal(some_str): 
    // handle byte literal case 
else: 
    // handle unicode case 
+5

您*不*有'some_str',你有'some_bytes'! – jonrsharpe

回答

13

最簡單的,也可以說,要做到這一點最好的辦法是通過利用內置isinstancebytes類型:

some_str = b'hello world' 
if isinstance(some_str, bytes): 
    print('bytes') 
elif isinstance(some_str, str): 
    print('str') 
else: 
    # handle 

因爲,一個字節字面意思是總是bytes,isinstance(some_str, bytes)的實例當然會評估爲True

4

只是爲了補充其他答案,內置的type也爲您提供這些信息。您可以使用它與is和相應的類型進行相應的檢查。

例如,在Python 3:

a = 'foo' 
print(type(a) is str) # prints `True` 
a = b'foo' 
print(type(a) is bytes) # prints `True` as well 
+4

使用'isinstance()'而不是直接與'type'比較的原因是['isinstance()'](https://docs.python.org/3/library/functions.html#isinstance)將會處理子類:子類「bytes」對象作爲「bytes」的實例仍然有效,但不會與「bytes」類型的有效比較。通常,'isinstance()'因此是首選。 – Evert