相关疑难解决方法(0)

在Python 3中将字符串转换为字节的最佳方法?

似乎有两种不同的方法将字符串转换为字节,如TypeError的答案所示:'str'不支持缓冲区接口

哪种方法更好或更好Pythonic?或者只是个人喜好?

b = bytes(mystring, 'utf-8')

b = mystring.encode('utf-8')
Run Code Online (Sandbox Code Playgroud)

python string character-encoding python-3.x

734
推荐指数
5
解决办法
110万
查看次数

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万
查看次数

Python3中的StringIO

我使用的是Python 3.2.1,我无法导入StringIO模块.我使用 io.StringIO和它的作品,但我不能使用它numpygenfromtxt是这样的:

x="1 3\n 4.5 8"        
numpy.genfromtxt(io.StringIO(x))
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

TypeError: Can't convert 'bytes' object to str implicitly  
Run Code Online (Sandbox Code Playgroud)

当我写import StringIO它时说

ImportError: No module named 'StringIO'
Run Code Online (Sandbox Code Playgroud)

python io python-3.x

407
推荐指数
7
解决办法
48万
查看次数

我如何gzip压缩Python中的字符串?

我如何gzip压缩Python中的字符串?

gzip.GzipFile 存在,但那是文件对象 - 用普通字符串怎么样?

python compression gzip

81
推荐指数
3
解决办法
6万
查看次数

标签 统计

python ×4

python-3.x ×3

string ×2

byte ×1

character-encoding ×1

compression ×1

file ×1

gzip ×1

io ×1