Python – How to use list inferences to replace commas with escaped commas in lists containing strings and numbers

How to use list inferences to replace commas with escaped commas in lists containing strings and numbers… here is a solution to the problem.

How to use list inferences to replace commas with escaped commas in lists containing strings and numbers

I

have a tuple that contains string and numeric elements, and I tried to replace the comma present in one of the tuple elements with an escaped comma, for example the input looks like this

('', 'i_like_cats', 'I like, cookies', 10319708L, "* / Item ID='10319708'", 'i_wish_was_an_oscar_meyer_weiner',
0.101021321)

The output I want is

('', 'i_like_cats', 'I like\, cookies', 10319708L, "* / Item ID='10319708'", 'i_wish_was_an_oscar_meyer_weiner',
0.101021321)

What I’d like to do is replace the after like , since I’m outputting the content to a csv file, so when the next step in the pipeline reads the file, it splits the file at the comma between ‘like’ and ‘cookies’, even if I don’t want it. I can’t modify the code for the downstream part of the pipeline, so I can’t switch to a file like a semicolon or tab-delimited file, nor can I change it.

What I’m trying to do is use list understanding to solve this problem as shown below

line = map(lambda x: str.replace(x, '"', '\"'), line)

But this generates a type error indicating that the replacement requires a string object, but it received a long integer.

The only solution I can think of is to break the tuple into separate elements, modify the element that contains the comma, and then build a new tuple and append each element back, but there seems to be a way to do this in a more pythonic way.

Thanks!

Solution

I think list understanding works best for applying rules for each element; If you know which string to change, why can’t you just change that string?

If you want to change all commas to escape commas, might as well try this:

strtuple = ('', 'i_like_cats', 'I like, cookies', 10319708, "* / Item ID='10319708'", 'i_wish_was_an_oscar_meyer_weiner',
0.101021321)
converted_strlist = [i.replace(',', '\\,') if isinstance(i, str) else i for i in strtuple]

Related Problems and Solutions