简体   繁体   English

Python替换文字\\ n

[英]Python replacing literal \n

I didn't want to ask here because I eventually got this to work, but I don't understand why my other attempts were not viable. 我不想在这里问这个问题,因为我最终做到了这一点,但是我不明白为什么我的其他尝试不可行。 It is driving me insane. 它让我发疯。 I looked up so many forums. 我查了很多论坛。

Currently I have 目前我有

filedata.replace('\\n','')

which removed literal \\n , followed by 删除文字\\n ,后跟

filedata = re.sub("': ;\d{5,6},\n'",', ',filedata)

to remove the subsequent "crap" in my output file 删除输出文件中的后续“废话”

I could not, for the life of me, put this into one command. 在我的一生中,我无法将这一命令付诸实践。 I don't know what I am missing, but this is because I cannot escape \\n in re.sub ( \\\\n does not work). 我不知道自己缺少什么,但这是因为我无法在re.sub转义\\n\\\\n不起作用)。 And, I cannot escape , in filedata.replace ; 而且,我无法逃避,filedata.replace ; \\, did not work, but \\' works to escape ' . \\,没有用,但是\\'逃脱的工作'

EDIT 编辑

Input: 输入:

Foo\nBarFoo,
Foo\nBarFoo

Desired Output: 所需输出:

FooBarFoo, FooBarFoo

This works: 这有效:

filedata = filedata.replace('\\n','')
filedata = re.sub(",\n",', ',filedata)

so the first line replaces literal \\n and second line replaces literal , and newline ( \\n ). 因此,第一行替换literal \\n ,第二行替换literal , \\n和换行符( \\n )。 What I could not do is get .replace to escape , ( \\, , etc. did not work) nor can I escape \\n (newline) in .sub ( \\\\n , etc. did not work). 我无法做的是获取.replace进行转义,\\,等不起作用),也无法在.sub转义\\n (换行符)( \\\\n等不起作用)。 So I had to do it in two different steps, while I would prefer to do both in one. 因此,我不得不分两个步骤进行操作,而我宁愿同时执行两个步骤。

I understand there are other ways to just remove characters if I am not actually replacing, this is just a simplified example of what I am doing. 我了解,如果我实际上没有替换,还有其他方法可以删除字符,这只是我正在做的简化示例。 Thanks. 谢谢。

Here are two "one-liners" but both require chaining two replace methods. 这里有两个“单线”,但是都需要链接两个替换方法。

>>> filedata = 'Foo\nBarFoo,\nFoo\nBarFoo'

>>> filedata.replace(',\n', ', ').replace('\n', '')
'FooBarFoo, FooBarFoo'

>>> filedata.replace('\n', '').replace(',', ', ')
'FooBarFoo, FooBarFoo'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM