Is there a way to ask for user input and turn their input into a list, tuple, or string for that matter? I want a series of numbers to insert into a matrix. I could tell them to type all the numbers into the console with no spaces and iterate through them but are there any other ways to do this?
To take list input in Python in a single line use input() function and split() function. Where input() function accepts a string, integer, and character input from a user and split() function to split an input string by space.
To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed.
a) split () This function is generally used to separate a given string into several substrings. However, you can also use it for taking multiple inputs. The function generally breaks the given input by the specified separator and in case the separator is not provided then any white space is considered as a separator.
You can simply do as follows:
user_input = input("Please provide list of numbers separated by comma, e.g. 1,2,3: ")
a_list = list(map(float,user_input.split(',')))
print(a_list)
# example result: [1, 2, 3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With