Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 501
user988126 Avatar asked Oct 19 '11 18:10

user988126


People also ask

Why string replace is not working in Python?

You are facing this issue because you are using the replace method incorrectly. When you call the replace method on a string in python you get a new string with the contents replaced as specified in the method call. You are not storing the modified string but are just using the unmodified string.

Does replace return a new string Python?

replace() method returns a copy of a string. This means that the old substring remains the same, but a new copy gets created – with all of the old text having been replaced by the new text.

How do you add a new line to a string in Python?

In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.

How do I replace a string in a string in Python?

Python String replace() Method The replace() method replaces a specified phrase with another specified phrase. Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.


2 Answers

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

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

like image 143
zunxunz Avatar answered Oct 17 '22 21:10

zunxunz


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!
like image 39
Steven Rumbalski Avatar answered Oct 17 '22 20:10

Steven Rumbalski