Appending a char to an empty list

Question:

I am very new to programming, so sorry for a basic question. I am trying to write a function that will take a string in which words are divided by ‘,’ and return a list of these words (the Split method). My code is:

def str_to_list(my_shop_str):
    
    my_shop_list = ['']
    word_in_list = 0
    for letter in my_shop_str:
        if letter != ',':
            my_shop_list[word_in_list] += letter
        else:
            word_in_list += 1
            my_shop_list + ['']
    return my_shop_list

print(str_to_list("Milk,Cottage,Tomatoes")) should look like [Milk, Cottage, Tomatoes]

but I am keep getting IndexError: list index out of range.
I read some answers here and couldn’t find something to work.
Can anyone explain what is wrong.

Asked By: Liran_T

||

Answers:

list has the method append so a solution will be something like this:

def str_to_list(my_shop_str):
    my_shop_list = ['']
    word_in_list = 0

    for letter in my_shop_str:
        if letter != ',':
            my_shop_list[word_in_list] += letter
        else:
            word_in_list += 1
            my_shop_list.append('')
    return my_shop_list

PS: Do not forgot about empty spaces between words in string like "aaa, bbb, ccc" will be ['aaa', ' bbb', ' ccc'] with spaces.

Answered By: idature
def sp(s):
    l =[]
    while True:
        comma = s.find(',')
        if comma == -1:
            l.append(s)
            break
        l.append(s[:comma])
        s = s[comma+1:]
    print(l)

this is a simplified version hope it helps.

Answered By: Aryman Deshwal

Simplest Way:
We can use an inbuilt split function.

def Convert(string):
    # split the string whenever "," occurs
    # store the splitted parts in a list
    li = list(string.split(","))
    return li
 
 
# Driver code
str1 = "Hello,World"
print(Convert(str1))

Output:
["Hello", "World"]

Answered By: Shivam Batra
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.