如何将字符串标识为字节文字?

Nat*_*ord 7 python string python-3.x

在Python 3中,如果我有一个字符串,那么:

print(some_str)
Run Code Online (Sandbox Code Playgroud)

得到这样的东西:

b'This is the content of my string.\r\n'
Run Code Online (Sandbox Code Playgroud)

我知道这是一个字节文字.

是否有一个函数可用于确定该字符串是否为字节文字格式(而不是具有,例如,Unicode 'u'前缀),而无需先解释?还是有另一个最佳实践来处理这个?我有一种情况,其中获取字节文字字符串需要处理不同于它是在Unicode中.从理论上讲,这样的事情:

if is_byte_literal(some_str):
    // handle byte literal case
else:
    // handle unicode case
Run Code Online (Sandbox Code Playgroud)

Jim*_*ard 14

最简单的,也可以说,这样做是利用最好的方式内置isinstancebytes类型:

some_str = b'hello world'
if isinstance(some_str, bytes):
    print('bytes')
elif isinstance(some_str, str):
    print('str')
else:
    # handle
Run Code Online (Sandbox Code Playgroud)

因为,文字将一个字节始终是一个实例bytes,isinstance(some_str, bytes)当然会,评估到True.


小智 5

只是为了补充另一个答案,内置程序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
Run Code Online (Sandbox Code Playgroud)

  • 使用 `isinstance()` 而不是直接与 `type` 比较的原因是 [`isinstance()`](https://docs.python.org/3/library/functions.html#isinstance) 将处理子类:子类化的 `bytes` 对象作为 `bytes` 的实例仍然有效,但与 `bytes` 类型相比无效。通常,`isinstance()` 因此是首选。 (4认同)