Search code examples
pythonstringlistformatting

convert a list into a single string consisting with double quotes and separated by comma


I have met a problem to convert a list: list=['1','2','3'] into ' "1","2","3" '.

My code is:

str(",".join('"{}"'.format(i) for i in list))

but my output is: "1","2","3" instead of ' "1","2","3" '

May I have your suggestion? Thanks.


Solution

  • I see you don't want to just prepend/append the needed substrings(the single quote and white space) to the crucial string.
    Here's a trick with str.replace() function:

    lst = ['1','2','3']
    result = "' - '".replace('-', ",".join('"{}"'.format(i) for i in lst))
    
    print(result)
    

    The output:

    ' "1","2","3" '
    

    • "' - '" - acts as a placeholder

    Or the same with additional str.format() function call:

    result = "' {} '".format(",".join('"{}"'.format(i) for i in lst))