python - str.translate() 替换空白字符
问题描述
我正在尝试使用 str.translate() 从打开的文件中的一行中删除 \t、\r 等。这在输入 Python 3 shell 时有效:
In [1]: def scrub_line(line):
...: import string
...: remap = {
...: ord('\t'): ' ',
...: ord('\f'): ' ',
...: ord('\n'): ' ',
...: ord('\r'): None,
...: }
...: return line.translate(remap)
In [2]: print(scrub_line("'pýtĥöñ\fIS\tawesome\r\n"))
'pýtĥöñ IS awesome
但是当我这样做时,它不适用于 shell 或单独的 python 文件:
In [3]: for line in open("text.txt"):
...: print(scrub_line(line))
...:
'pýtĥöñ\fIS\tawesome\r\n
Assignment is defined recursively depending on the form of the target (list). When a target is part of a mutable object (an attribute reference, subscription or slicing), the mutable object must ultimately perform the assignment and decide about its validity, and may raise an exception if the assignment is unacceptable. The rules observed by various types and the exceptions raised are given with the definition of the object types (see section The standard type\fhierarchy).
An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to \r right.
remap
我在第二行和第三行从上表中插入了一些随机字符。
菜鸟在这里,我没有得到什么?
解决方案
推荐阅读
- javascript - 更改刚刚创建的频道的权限
- android - ndk-build 文件未找到但被调用
- algorithm - 任何线性算法的 Big Omega 是 n 还是也可以是 1?
- javascript - vue cli - Uncaught SyntaxError: Unexpected token <
- sql-server - SQL Server BAK 文件在记事本中打开
- python - Python 2.7 ascii' 编解码器无法编码字符 u'\xe4
- postman - 示例发布请求中的令牌错误
- api - Cuckoo沙箱,安装后api报错
- php - 转移到另一台服务器后PHPMailer失败
- c# - 自动映射时是否可以展平对象的某些部分