Python。如何去掉字符串中的“\r”?

2024-04-26 08:00:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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'

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

我想我知道一种从字符串中删除该字符串的方法,但我想从源代码修复该问题


Tags: 文件字符串intesttxt元素列表for
3条回答

如果您确定最后一个字符总是\r,请使用rstrip()rstrip('\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()同时删除尾随空格和前导空格。

要接受\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)

您可以使用strip()从行中除去回车和换行符

line.strip()

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

相关问题 更多 >