Home > Software design >  Join list into string by preserving quotes if present
Join list into string by preserving quotes if present

Time:12-12

Example

items = ['"1,2"', "3", "4"]

Expected output:

"1,2", 3, 4 # join bypreserving quotes

I have tried

",".join(items)

But it gives:

"1, 2, 3, 4" 

Is there a hint for a way to do this?

CodePudding user response:

If you are trying to convert int but keep strings as it is, then this would help :

def foo(bar : list) -> list:
    x = list()
    for i in bar:
        try:
            x.append(int(i))
        except:
            x.append(i)
    return x

Result (matching your expected result) :

>>>items = ["1,2", "3", "4"]
>>>foo(items))
['1,2', 3, 4]

It seems like you are trying to work with csv files, if that's the case then using the in-built csv module will help.

CodePudding user response:

Use json.dumps to get it along with quotes:

import json
items = ["1,2", "3", "4"]
json.dumps(items)
  • Related