相关疑难解决方法(0)

'b'字符在字符串文字前面做了什么?

显然,以下是有效的语法

my_string = b'The string'
Run Code Online (Sandbox Code Playgroud)

我想知道:

  1. 这是什么b字在前面的字符串是什么意思?
  2. 使用它有什么影响?
  3. 使用它的适当情况是什么?

我在SO上找到了一个相关的问题,但是这个问题是关于PHP的,它表示b用于表示字符串是二进制的,而不是Unicode,这是代码与PHP版本兼容所需的代码<6 ,当迁移到PHP 6.我不认为这适用于Python.

我确实在Python网站上找到了关于使用相同语法的字符将字符串指定为Unicode的文档u.不幸的是,它没有提到该文档中任何地方的b字符.

而且,只是出于好奇,有没有比多符号bu是做其他事情?

python string unicode binary

724
推荐指数
10
解决办法
49万
查看次数

TypeError:在Python3中写入文件时需要类似字节的对象,而不是'str'

我最近迁移到了Py 3.5.这段代码在Python 2.7中正常工作:

with open(fname, 'rb') as f:
    lines = [x.strip() for x in f.readlines()]

for line in lines:
    tmp = line.strip().lower()
    if 'some-pattern' in tmp: continue
    # ... code
Run Code Online (Sandbox Code Playgroud)

升级到3.5后,我得到了:

TypeError: a bytes-like object is required, not 'str'
Run Code Online (Sandbox Code Playgroud)

最后一行的错误(模式搜索代码).

我已尝试.decode()在语句的任何一侧使用该函数,也尝试过:

if tmp.find('some-pattern') != -1: continue
Run Code Online (Sandbox Code Playgroud)

- 无济于事.

我能够迅速解决几乎所有2:3的问题,但这个小小的陈述让我烦恼.

python string byte file python-3.x

497
推荐指数
10
解决办法
90万
查看次数

标签 统计

python ×2

string ×2

binary ×1

byte ×1

file ×1

python-3.x ×1

unicode ×1