【问题标题】:How to identify a string as being a byte literal?如何将字符串标识为字节文字?
【发布时间】:2016-09-29 19:59:29
【问题描述】:

在 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

【问题讨论】:

  • 没有some_str,你有some_bytes

标签: python string python-3.x


【解决方案1】:

最简单且可以说是最好的方法是使用内置的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

【讨论】:

  • @Fardin 是的,因为 byte 在 Python 2 中并不是真正的字节文字;使用b'...''...' 会产生同样的结果。除此之外,这个问题明确要求 Python 3。
【解决方案2】:

为了补充其他答案,内置的 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

【讨论】:

  • 使用isinstance()而不是直接与type比较的原因是isinstance()将处理子类:子类bytes对象作为bytes的实例仍然有效,但与bytes 类型相比无效。通常,因此首选isinstance()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-23
  • 1970-01-01
  • 2023-02-26
  • 1970-01-01
  • 1970-01-01
  • 2017-04-16
  • 2014-04-29
相关资源
最近更新 更多