Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Replace, rstrip() not able to remove newlines

I've got a spreadsheet of information (UTF-8 CSV file being read in by the csv module) that contains information for a large number of products that need to go into an inventory db. I'm trying to setup descriptions from newlined rows of text to a html list tags.

The issue I'm having is that the following lines fail to replace the newline character in the string:

line[2] = "<ul><li>" + line[2]
line[2].replace('\n', '</li><li>')
line[2] += "</li></ul>"

The string continues to contain newline characters even when the second line is replaced by:

line[2] = line[2].rstrip()

What is going on, and what am I messing up? =)

like image 885
James Christie Avatar asked Jun 13 '26 15:06

James Christie


2 Answers

From python manual

str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

As you can see, it doesn't replace "in place", instead, try:

line[2] = "<ul><li>" + line[2]
line[2] = line[2].replace('\n', '</li><li>')
line[2] += "</li></ul>"
like image 174
arthurprs Avatar answered Jun 15 '26 03:06

arthurprs


Replace isn't in place.

So do

line[2] = "<ul><li>" + line[2].replace('\n', '</li><li>') + "</li></ul>"
like image 40
dr jimbob Avatar answered Jun 15 '26 05:06

dr jimbob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!