简体   繁体   中英

How to print the items in a list, given through input?

I have a variable that saves the user's input. If the user inputs a list, eg ["oranges","apples","pears"] python seems to take this as a string, and print every character, instead of every word, that the code would print if fruit was simply a list. How do I the code to do this? Here is what I've tried...

fruit = input("What is your favourite fruit?")
fruit = list(fruit)
for i in fruit:
  print(i)

python takes inputs as one huge string so instead of that being a list it is just a string like that looks like this

'["oranges","apples","pears"]'

turning this into a list will just look like

['[', '"', 'o', 'r', 'a', 'n', 'g', 'e', 's', '"', ',', '"', 'a', 'p', 'p', 'l', 'e', 's', '"', ',', '"', 'p', 'e', 'a', 'r', 's', '"', ']']

instead of this try something like this which asks for favourite fruits until you do not enter a fruit

Fruits = []
while True:
    temp = input()
    if temp == "":
        break
    else:
        Fruits.append(temp)

and then output the values

for x in Fruits:
    print(x)

You will have to split word is list by comma.

fruit = list(fruit.split(","))


fruit = input("What is you favourite fruit?")
fruit = fruit.split(",")
for i in fruit:
  print(i)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM