-1

I have a following string:

s_tring = 'abcd,efgh,igkl,mnop,qrst,uvwx,yz'

I want to create a list and split it by commas and put quotes around each element like this:

some_list = '"abcd", "efgh", "igkl", "mnop", "qrst", "uvwx", "yz"'

I have tried doing something like this:

some_list = '","'.join(s_tring)

But it doesn't work.

quamrana
  • 37,849
  • 12
  • 53
  • 71
Archi
  • 79
  • 8
  • Please update your question with the code you have tried. – quamrana Oct 10 '21 at 14:58
  • I recommend looking into [str.split](https://docs.python.org/3/library/stdtypes.html#str.split) and [str.join](https://docs.python.org/3/library/stdtypes.html#str.join), or alternatively [the csv module](https://docs.python.org/3/library/csv.html) – Stef Oct 10 '21 at 15:02
  • A duplicate of - https://stackoverflow.com/questions/45208090/python-how-to-append-double-quotes-to-a-string-and-store-as-new-string/45208151 – tidakdiinginkan Oct 10 '21 at 15:02
  • 2
    What you're describing sounds a lot like CSV. Python has a standard-library module that implements the format properly. – Charles Duffy Oct 10 '21 at 15:02

4 Answers4

1

You must first split the original string into a list of strings and then you can put the quotes round them and finally join with a comma:

s_tring = 'abcd,efgh,igkl,mnop,qrst,uvwx,yz'
parts = s_tring.split(',')
parts = [f'"{part}"' for part in parts]
some_list = ', '.join(parts)

An alternative is to join the parts with quotes as well and finally add the missing quotes:

s_tring = 'abcd,efgh,igkl,mnop,qrst,uvwx,yz'
parts = s_tring.split(',')
some_list = '"' + '", "'.join(parts) + '"'
print(some_list)
quamrana
  • 37,849
  • 12
  • 53
  • 71
1

Just split & join

string = 'abcd,efgh,igkl,mnop,qrst,uvwx,yz'
string = ', '.join([f'"{x}"' for x in string.split(',')])
print(string)

output

"abcd", "efgh", "igkl", "mnop", "qrst", "uvwx", "yz"
balderman
  • 22,927
  • 7
  • 34
  • 52
1

In a single line using the split and join methods with a list comprehension.

s = 'abcd,efgh,igkl,mnop,qrst,uvwx,yz'

print(', '.join([f'"{w}"' for w in s.split(',')]))
# '"abcd", "efgh", "igkl", "mnop", "qrst", "uvwx", "yz"'
Dan Nagle
  • 4,384
  • 1
  • 16
  • 28
0

Logic: First let's create a new variable which is empty string in which we can add elements until we get a "," using loop. If we get a "," then we'll change it to a space (" ") and add it to variable so that after completion of loop, we can use split() function to remove spaces and append it to an empty list. Your code would be:

x="abcd,efgh,ijkl,mnop,qrst"
v=""
l=[]
c=0
for i in x:
    if i==",":
        v+=" "
    else:
        v+=i

 for b in v.split():
    l.append(b)
        

print(l)

Or simply use split(",") and add