简体   繁体   中英

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

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). And, I cannot escape , in 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 ). 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). 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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