简体   繁体   中英

How can I use list comprehension to replace a comma with an escaped comma in a list that contains strings and numbers

I have a tuple that contains elements that are both strings and numbers, and I am trying to replace a comma that exists in one of the elements of the tuple with an escaped comma, eg the input looks like the following

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

and what I want as output is

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

What I want to do is replace the , after like with /, because I'm outputting the content to a csv file, so when the next step of the pipeline reads the file it splits the file at the comma between 'like' and 'cookies' even though I don't want it to. I am unable to modify the code of the downstream part of the pipeline so I can't switch to something like a semicolon or tab delimited file, and I can't change.

What I've tried to do is use list comprehension to solve this as follows

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

but that generates a type error indicating that replace requires a string object but it received a long.

The only solution I can think of is to break the tuple down into it's individual elements, modify the element that contains the comma, and then build a new tuple and append each of the elements back on, but it seems like there has to be a more pythonic way to do that.

Thanks!

I think list comprehension works the best for apply a rule for every element; if you know which single string you would like to change, why can't you just change that single one?

If you want to change all comma into escaped comma, probably try this out:

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]

You might want to verify an element is a str instance before calling replace on it.

Something like:

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

    line = [
        x.replace(",", "\,") if isinstance(x, str) else x for x in data
    ]

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