简体   繁体   中英

Python User Input To List Separated Values

I've been trying to create a script that:

  • Asks a user to input keywords
  • Stores the user's input in a list
  • Prints each value from the list

When I try to print the list all the values seem to be under the index 0

inputwords = input('What keywords are you looking for?').split()
inputwordslist = []

inputwordslist.append(inputwords)
inputwordslist = enumerate(inputwordslist)
print (list(inputwordslist))

Output Below:

What keywords are you looking for?This is a test
[(0, ['This', 'is', 'a', 'test'])]

For the easiest solution to your problem, @Chris_Rands already posted it in a comment to your question: .split() returns a list. You don't have to make a separate one for the result, just enumerate the value returned by the split function:

inputwords = input('What keywords are you looking for?').split()
result = list(enumerate(inputwords))
print(result)

What keywords are you looking for? This is a list of words.
[(0, 'This'), (1, 'is'), (2, 'a'), (3, 'list'), (4, 'of'), (5, 'words.')]

As noted in the other answer, it is a good idea to put a space after your prompt, that way there is separation between it and what the user is typing in:

inputwords = input('What keywords are you looking for? ').split()

Your code will not work with python2 though, where the input() function is actually running the resulting string through eval() :

>>> input()

1 + 2 + 3
6

For more information, see this question .

If you want your code to be compatible with both python2 and python3, use this little snippet:

try:                       
    input = raw_input      
except NameError:          
    pass                   

This will make sure that input is pointing to the python3 version of the function.

The result of input(...).split() is a list. Therefore all you need is:

inputwords = input('What keywords are you looking for?').split()
print(list(enumerate(inputwords)))

Note that while this works in Python 3, in Python 2 you would have to use the raw_input() function instead - input expects a Python expression, and returns the result of evaluating that expression.

>>> inputwords = input('What keywords are you looking for?').split()
What keywords are you looking for?This, that and the other
>>> print(list(enumerate(inputwords)))
[(0, 'This,'), (1, 'that'), (2, 'and'), (3, 'the'), (4, 'other')]

It's helpful to put a space at the end of your prompt string, to clearly separate the prompt and the input.

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