Home > Software design >  How do I split up a user input so that it takes up two index places in an array? (Python)
How do I split up a user input so that it takes up two index places in an array? (Python)

Time:12-10

I am looking to be able to take a user input of a few different words separated by commas, and then add them to an array so that each word they've put in takes up a different index value. This is the function I am using for this:

array = ["cat","dog","house","car"]
print(array)

def append():#accepts a user input and adds it to the array
item = input("What would you like to append: ")
item = item.lower()
array.append(item)#appends the item variable delcared in the above statement
print ("The list is now: ",array)

Currently, this works by taking one user input, changing it to lowercase, adding it to the array and printing it out. I want to have it so the user can input: mouse, horse, mountain and the program will add those three items to the array all separately. At the moment it adds them all together - as it should. I've tried the split() command however all that seems to do is add them as one thing and just put square brackets around them.

Any help would be great. Cheers

CodePudding user response:

You can use split func:

lst = string.split(", ")

It returns a list of strings.

input:

Apple, Facebook, Amazon

lst:

["Apple", "Facebook", "Amazon"]

Update

After you get the list, you can add them to the the main list (whatever you call it):

array  = lst

Now array contains these:

["cat","dog","house","car","Apple", "Facebook", "Amazon"]

CodePudding user response:

something like this

lst = ["cat","dog","house","car"]

def append():
  item = input("What would you like to append: ")
  lst.extend(item.lower().split(','))
 
print(f'Before: {lst}')
append()
print(f'After: {lst}')

CodePudding user response:

You are thinking in the right direction, as one answer pointed out that you can use .split() method I will try to explain it a little more. You can create an item list to store the list of strings to be appended. Something like this

```python
item = input("What would you like to append: ")
item_list=item.split(", ")
```

Now you can use for loop to append this list your original array. Something like this..

```python
for item in item_list:
    item=item.lower()
    array.append(item)
```

Whole code for reference..

```python
array = ["cat","dog","house","car"]
print(array)

def append():#accepts a user input and adds it to the array
   item = input("What would you like to append: ")
   item_list=item.split(", ")
   for item in item_list:
       item = item.lower()
       array.append(item)     #appends the item variable
print ("The list is now: ",array)```
  • Related