带 \n 的 Python 条带 [英] Python strip with \n
问题描述
这是我的问题.
我正在尝试读取文本文件,然后将行转换为浮点数.文本文件中有 \n
和 \t
虽然我不知道如何摆脱它.
I'm trying to read a text file and then convert the lines into floats. The text file has \n
and \t
in it though I don't know how to get rid of it.
我尝试使用 line.strip()
但它没有去掉,当我想将内容转换为浮点数时出现错误.然后我尝试了 line.strip("\n")
但这也不起作用.当我从文本文件中取出 \t
和 \n
时,我的程序运行良好,但这是让它与它们一起工作的任务的一部分.
I tried using line.strip()
but it didn't take it off and I got an error when I wanted to convert the stuff to floats. I then tried line.strip("\n")
but that didn't work either. My program works fine when I take out the \t
and \n
from the text file, but it's part of the assignment to get it to work with them.
我真的不知道为什么这不起作用.谢谢你的帮助.
I really don't know why this isn't working. Thanks for any help.
推荐答案
你应该能够使用 line.strip('\n')
和 line.strip('\t')
.但是这些不会修改 line
变量……它们只是返回去除了 \n
和 \t
的字符串.所以你必须做类似的事情
You should be able to use line.strip('\n')
and line.strip('\t')
. But these don't modify the line
variable...they just return the string with the \n
and \t
stripped. So you'll have to do something like
line = line.strip('\n')
line = line.strip('\t')
这应该适用于从头到尾删除.如果字符串中间有 \n
和 \t
,则需要做
That should work for removing from the start and end. If you have \n
and \t
in the middle of the string, you need to do
line = line.replace('\n','')
line = line.replace('\t','')
将 \n
和 \t
替换为虚无.
to replace the \n
and \t
with nothingness.
这篇关于带 \n 的 Python 条带的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!