Home > Back-end >  Python: How to join a list of strings to form one string while including commas within the strings
Python: How to join a list of strings to form one string while including commas within the strings

Time:01-08

For example

lista = ['one', 'two', 'three,4']
s_headers = ','.join([str(elem) for elem in lista])

Desired output

"one, two, 'three,4'"

Seen output

"one, two, three, 4"

CodePudding user response:

You can include an if-else condition inside generator expression to add 's:

s_headers = ','.join('\'' elem '\'' if ',' in elem else elem for elem in lista)

Output:

"one,two,'three,4'"

CodePudding user response:

I don't know why you would want this unless you were writing a CSV file, and as I said, the Python csv module will handle this for you.

However:

def quote(s):
    if ',' in s:
        return f"'{s}'"
    else:
        return s

lista = ['one', 'two', 'three,4']
s_headers = ','.join(quote(elem) for elem in lista)

CodePudding user response:

You need to add condition in order to do that

','.join([str(elem) if "," not in elem else f"'{str(elem)}'" for elem in lista])

output: "one,two,'three,4'"

CodePudding user response:

You will have to check if your desired separator is part of any of your strings:

def join_quoted(strings, separator=',', quote_char="'"):
    quoted = [f'{quote_char}{s}{quote_char}' if separator in s else s for s in strings]
    return separator.join(quoted)

join_quoted(lista)

gives

"one,two,'three,4'"

CodePudding user response:

def join_list(list):
# create a new list to hold the new strings
new_list = []

for element in list:
    if isinstance(element, str) and ',' in element:
        element = '"'   element   '"'
    new_list.append(element)

new_list = ', '.join(new_list)
return new_list

list = ["one", "two", "three,4"]

print(join_list(list))

  •  Tags:  
  • Related