在python的字符串末尾替换换行符

时间:2018-09-05 06:31:50

标签: python-2.7

我的桌面上有一个文本文件,仅包含以下行

"C:\Users\Administrator\Desktop\Test\not-84949685 .txt_Fetched.txt\n"

在那,我只想在行尾仅删除“ \ n” 为此,我写的代码为

List = "C:\\Users\\Pavithran\\Desktop\\list.txt"
with open(List,'r') as readfile:
     content = readfile.readlines()
for i in content:
    i = i.replace ("\\n","")
    print i

该代码的输出:

"C:\Users\Administrator\Desktop\Testot-84949685 .txt_Fetched.txt"

它还会在测试后替换\ n。

预期输出:

"C:\Users\Adminstrator\Desktop\Test\not-84949685 .txt_Fetched.txt"

2 个答案:

答案 0 :(得分:0)

re.sub与模式\n(?="$)配合使用,以专门针对输入末尾出现的换行符。

input = "\"C:\\Users\\Administrator\\Desktop\\Test\\not-84949685 .txt_Fetched.txt\n\""
print(re.sub(r"\n(?=\"$)", "", input))
print("Hello World!")

"C:\Users\Administrator\Desktop\Test\not-84949685 .txt_Fetched.txt"
Hello World!       <-- I added this to show that the newline was removed

Demo

答案 1 :(得分:0)

@Tim的解决方案很优雅,可以解决此类问题。

顺便说一句,如果您只想删除最后一个字符(是'\n'只是一个字符而不是两个字符),则可以使用Python字符串切片:

List = "C:\\Users\\Pavithran\\Desktop\\list.txt"

with open(List,'r') as readfile:
    for line in readfile:
        line = line[:-1]

变量line现在包含预期的输出。