user988126
user988126

Reputation: 101

Python string replace not working new lines

I have a keywords file I just wanted to replace the new lines with commas

print file("keywords.txt", "r").read().replace("\n", ", ")

tried all variations of \r\n

Upvotes: 5

Views: 12062

Answers (8)

Flagship Dynamics
Flagship Dynamics

Reputation: 71

Search on double slash n instead of \n. That cost hours of my life. This website even changes it to \n when I tried to paste it. The combo that shall not be spoken. ""+""+"n" would be the string combo to try to explain it.

Upvotes: 0

Hlodowig91
Hlodowig91

Reputation: 11

I had this problem too and solve it with :

new_text = ",".join(text.split("\n"))

My "\n" wasn't interpreted in the same way between my unit test (with str as input) and my integration test (with file reading import as input), so str.replace("\n", ",") didn't work with both tests.

EDIT => With both this works too :

text = text.replace("\\n", ",")
text = text.replace("\n", ",")

I don't know why is it different between file and str input...

Upvotes: 0

Dejan Dozet
Dejan Dozet

Reputation: 1009

I've just had the same problem and this was the solution to it:

phones = arr[8].replace("\\n", "|")

Upvotes: 0

zunxunz
zunxunz

Reputation: 51

Don't forget, this is Python! Always look for the easy way...

', '.join(mystring.splitlines())

Upvotes: 5

Steven Rumbalski
Steven Rumbalski

Reputation: 45542

Your code should work as written. However, here's another way.

Let Python split the lines for you (for line in f). Use open instead of file. Use with so you don't need to close the file manually.

with open("keywords.txt", "r") as f:
    print ', '.join(line.rstrip() for line in f) # don't have to know line ending!

Upvotes: 2

chown
chown

Reputation: 52738

Did you want to replace the actual file contents? Like this:

newContent = file("keywords.txt", "r").read().replace("\r", "").replace("\n", ", ")
open("keywords.txt", "w").write(newContent)

Upvotes: 0

jwd
jwd

Reputation: 11114

The code you wrote works for me in a test file I created.

Are you trying to write the results back to a file?

You could try looking at the input file in a hex editor to see the line endings.

Upvotes: 0

Di Zou
Di Zou

Reputation: 4609

I just tried this and it works for me. What does your file look like?

My "temp.txt" file looked like this:

a
b
c
d
e

and my python file had this code:

print file("temp.txt", "r").read().replace("\n", ", ")

This was my output:

>python temp_read.py
a, b, c, d, e,

Upvotes: 0

Related Questions