Python。如何摆脱字符串中的'\ r'?

时间:2012-12-01 05:01:17

标签: python string list replace

我有一个excel文件,我将其转换为带有数字列表的文本文件。

test = 'filelocation.txt'

in_file = open(test,'r')

for line in in_file:
    print line

1.026106236
1.660274766
2.686381002
4.346655769
7.033036771
1.137969254

a = []

for line in in_file:
    a.append(line)
print a

'1.026106236\r1.660274766\r2.686381002\r4.346655769\r7.033036771\r1.137969254'

我想将每个值(在每一行中)分配给列表中的单个元素。而是创建一个由\ r分隔的元素。我不确定\ r是什么,但为什么要将这些放入代码?

我想我知道从字符串中删除\ r \ n的方法,但我想从源代码修复问题

6 个答案:

答案 0 :(得分:5)

要接受任何\r\n\r\n作为换行符,您可以使用'U'(通用换行符)文件模式:

>>> open('test_newlines.txt', 'rb').read()
'a\rb\nc\r\nd'
>>> list(open('test_newlines.txt'))
['a\rb\n', 'c\r\n', 'd']
>>> list(open('test_newlines.txt', 'U'))
['a\n', 'b\n', 'c\n', 'd']
>>> open('test_newlines.txt').readlines()
['a\rb\n', 'c\r\n', 'd']
>>> open('test_newlines.txt', 'U').readlines()
['a\n', 'b\n', 'c\n', 'd']
>>> open('test_newlines.txt').read().split()
['a', 'b', 'c', 'd']

如果要从文件中获取数字(浮点)数组;见Reading file string into an array (In a pythonic way)

答案 1 :(得分:2)

如果您确定最后一个字符始终为rstrip(),请使用rstrip('\r')\r

for line in in_file:
    print line.rstrip()

str.rstrip()上的帮助:

S.rstrip([chars]) -> string or unicode

Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping

str.strip()删除尾随和前导空格。

答案 2 :(得分:0)

您可以使用strip()

从行中删除回车符和换行符
line.strip()

for line in in_file:
    a.append(line.strip())
print a

答案 3 :(得分:0)

要解决此问题,请执行以下操作:

for line in in_file:
    a.append(line.strip())

答案 4 :(得分:0)

.strip()删除不需要的空格的行:

lines = []

with open('filelocation.txt', 'r') as handle:
    for line in handle:
        line = line.strip()
        lines.append(line)

        print line

print lines

另外,我建议您使用with ...表示法打开文件。它更干净并自动关闭文件。

答案 5 :(得分:0)

首先,我一般喜欢@ J.F. Sebastian的答案,但我的用例更接近Python 2.7.1: How to Open, Edit and Close a CSV file,因为我的字符串来自 text 文件,从Excel输出为csv,并且还使用csv模块输入。如该问题所示:

  

对于'rU'vs'rb'vs ...,csv文件确实应该是二进制的   用'rb'。但是,从某人那里获得csv文件并不罕见   将它复制到Windows上的记事本中,之后又加入了一些   其他文件,所以你有时髦的行结尾。你是如何处理的   取决于您的文件和您的偏好。 - @kalhartt 1月23日3:57

我将按照the python docs中的建议坚持阅读'rb'。现在,我知道单元格中的\ r是由于我如何使用Excel的怪癖,所以我只是创建一个全局选项,用其他东西替换'\ r',现在将是' \ n',但后来可能是''(一个空字符串,而不是双引号),带有简单的json更改。

相关问题