Zizma Zizma -4 years ago 184
Python Question

How to assign user input to a variable or list

Let's say that I have a line with:

a = input("Enter your name and age:")

How can I make the variable "a" store each section of the input, lets say "George 25" as "George, 25" either as a standard variable or a list? All I want to do is be able to store user input as separate elements in a list or variable so that input with words separated by a space would become separate elements in a variable. Is this clear enough? I am using Python 3.0

Answer Source

How about using str.split():

user_input_list = input("Enter your name and age:").split(' ')

This creates a list of each space-separated word in the input.

>>> 'George 25'.split(' ')
['George', '25']

Then you can access each part as:

user_input_list[0] # George
user_input_list[1] # 25

Is that what you're after ?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download