【问题标题】:creating a byte string in python在python中创建一个字节字符串
【发布时间】:2017-09-29 13:54:12
【问题描述】:

我正在尝试创建一个字节字符串,但它似乎只是一个常规字符串。我在这里做错了什么?

byteStr = b'some string'
byteStr #'some string'
utfStr = 'some string'.encode('utf-8')
utfStr #'some string'
byteStr == utfStr #True

【问题讨论】:

  • 您的字节串创建正确;仅仅因为它等于一个字符串并不意味着那是错误的。我不会回答,因为我不知道字节串是如何工作的,但比较字节串和字符串(通常)会给出True
  • @HyperNeutrino 已更新,我期待 byteStr 的打印在第一个引号之前显示 b,并且等效性测试失败
  • @HyperNeutrino 我也看到了,当我运行 type(byteStr) 时,我会返回 。对吗?
  • @anonymousPerson....感谢随机投票

标签: python-2.7 cmd


【解决方案1】:

如果您尝试在 Python 2 中创建一个字节数组,它被称为 bytearrayPython 2 does not have a byte string.The b in front of the str is ignored in Python 2,意思是'hello' == b'hello'

试试这个:

>>> f = b'f'
>>> type(f)
<type 'str'>

现在,重要的是要记住u'f' == 'f'

>>> h = u'f'
>>> f == h
True
>>> type(h)
>>> <type 'unicode'>

【讨论】:

  • 啊,我明白了。我正在遵循的教程使用 python3 来解释差异。谢谢!
  • 作为一个快速跟进的问题,为什么我的示例中的 type(uftStr) 会返回 而不是 ?似乎 .encode('utf-8') 函数不起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-20
  • 1970-01-01
相关资源
最近更新 更多