String 如何从行中删除\n?
我正在从文件中读取行并将它们放入列表中。但是,当我读这些行时,它们会以换行符(String 如何从行中删除\n?,string,python-2.7,String,Python 2.7,我正在从文件中读取行并将它们放入列表中。但是,当我读这些行时,它们会以换行符(\n)读入。我试图用str.strip(),str.rstrip(),str.strip(“\n”),str.rstrip(“\n”),str.strip(\\n”),和str.rstrip(\\n”),删除它,但是 他们中没有一个人做了我希望他们做的事。 这是代码 lines=[] with open(v) as x: for line in x: if "\n" in line:
\n
)读入。我试图用str.strip()
,str.rstrip()
,str.strip(“\n”)
,str.rstrip(“\n”)
,str.strip(\\n”)
,和str.rstrip(\\n”)
,删除它,但是
他们中没有一个人做了我希望他们做的事。
这是代码
lines=[]
with open(v) as x:
for line in x:
if "\n" in line:
lines.append(line)
for line in lines:
line.strip()
if '\n' in line:
print "I'm a stupid computer."
print lines
这正好产生了这个输出
I'm a stupid computer.
I'm a stupid computer.
I'm a stupid computer.
I'm a stupid computer.
I'm a stupid computer.
I'm a stupid computer.
I'm a stupid computer.
I'm a stupid computer.
I'm a stupid computer.
I'm a stupid computer.
['6\n', '1 2\n', '2 3\n', '3 1\n', '10 11\n', '100 10\n', '11 100\n', '1 100\n', '2 3\n', '3 2\n']
我不确定我遗漏了什么。line.strip()创建了一个没有前导/尾随空格的行的副本。您没有对副本执行任何操作,您需要将其分配回该行。你想要:
line=line.strip()
您也可以使用:
with open(v) as fin:
lines = [line.strip() for line in fin.readlines()]
您可能不希望只添加包含换行符的行。也许您想要的是省略那些不包含任何其他内容的行:
with open(v) as fin:
lines = [line.strip() for line in fin.readlines() if line.strip()]
line.strip()创建不带前导/尾随空格的行的副本。您没有对副本执行任何操作,您需要将其分配回该行。你想要:
line=line.strip()
您也可以使用:
with open(v) as fin:
lines = [line.strip() for line in fin.readlines()]
您可能不希望只添加包含换行符的行。也许您想要的是省略那些不包含任何其他内容的行:
with open(v) as fin:
lines = [line.strip() for line in fin.readlines() if line.strip()]
您需要将
strip()
的输出分配回变量:
line=line.strip()
line=line.strip()line.strip()
不会更改line
;它返回一个剥离的副本。改为使用line=line.strip()
(或者更好的是,对于您的示例,只需首先将剥离的版本附加到列表中:
if "\n" in line:
lines.append(line.strip())
字符串对象在Python中是不可变的。line.strip()
不会改变line
;它返回一个剥离的副本。使用line=line.strip()
(或者更好的是,对于您的示例,只需首先将剥离的版本附加到列表中:
if "\n" in line:
lines.append(line.strip())
\n是一个字符,可以对其进行切片
line = line[0:len(line)-1]
或者根据@Henry的评论
line[:-1]
\n是一个字符,可以对其进行切片
line = line[0:len(line)-1]
或者根据@Henry的评论
line[:-1]
或者line=line[:-1]
。但这并不是问题的核心,也就是OP不了解条带()的内容
method确实如此。我也喜欢这个解决方案,但我选择Henry的解决方案只是因为它解释了我所缺少的部分。不过,这对于未来来说是个好消息。谢谢。或者line=line[:-1]
。但这并不是问题的核心,因为OP不理解条带()
method确实如此。我也喜欢这个解决方案,但我之所以选择Henry的解决方案,只是因为它解释了我缺少的部分。不过,很高兴知道这一点,以备将来使用。谢谢。