str.translate()替换空白字符

时间:2018-12-25 17:27:49

标签: python python-3.x string

我正在尝试使用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 

但是当我这样做时,它不能从外壳程序或单独的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表的第二和第三行中插入了一些随机字符。

Noob在这里,我没得到什么?

0 个答案:

没有答案
相关问题