toastrackengima
toastrackengima

Reputation: 8722

Problems making arrays with user input in Python

I've got a window using tkinter where the user can type in the value for an array: i.e. "x","y","z". Then when I go to put that data into an array (myarray = [myuserinput]) it puts two single quotes around it like this: '"x","y","z"'. This prevents the array from being able to be read - IndexError: list index out of range
Also, when I try to make another array using some data and a while loop it inserts alot of brackets infront of it:

    firstcounter = "1"
    thecounters = "0"
    while int(firstcounter) < newfilter :
        thecounters = thecounters,0
        firstcounter = int(firstcounter) + 1
    counters = [thecounters]

This code also results in an list index out of range error

Please Help!!!!

Upvotes: 0

Views: 86

Answers (1)

msvalkon
msvalkon

Reputation: 12077

I'll make a wild guess here and assume that you're dealing with a string in which the elements are delimited by a ,.

You'll need to split the string to get a list of the elements.

myarray = myuserinput.split(",")

Example:

In [3]: myuserinput = '"x","y","z"'

In [4]: my_list = myuserinput.split(",")

In [5]: my_list
Out[5]: ['"x"', '"y"', '"z"']

You can replace the "" before you split:

In [11]: myuserinput = myuserinput.replace('"', '')

In [12]: myuserinput
Out[12]: 'x,y,z'

Upvotes: 1

Related Questions