首页 > 解决方案 > 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我在第二行和第三行从上表中插入了一些随机字符。

菜鸟在这里,我没有得到什么?

标签: pythonpython-3.xstring

解决方案


推荐阅读