Python3 – list() is taking every character in the string as an element, not every word
Question:
I want to make a list of numbers via input
When I type:
>>> list(input())
1 23 456 7890
['1', ' ', '2', '3', ' ', '4', '5', '6', ' ', '7', '8', '9', '0']
how to let it print this:
[1, 23, 456, 7890]
?
Answers:
You can try:
>>> list(input().split(" "))
1 23 456 7890
['1', '23', '456', '7890']
If you want all elements as int in list, you can try:
>>> list(map(int, list(input().split(" "))))
1 2 34 567 890
[1, 2, 34, 567, 890]
You can try
[int(e) for e in input().split()]
This is a list comprehension that converts all split string in integers. It will raise an exception if string can not be converted to integers.
I want to make a list of numbers via input
When I type:
>>> list(input())
1 23 456 7890
['1', ' ', '2', '3', ' ', '4', '5', '6', ' ', '7', '8', '9', '0']
how to let it print this:
[1, 23, 456, 7890]
?
You can try:
>>> list(input().split(" "))
1 23 456 7890
['1', '23', '456', '7890']
If you want all elements as int in list, you can try:
>>> list(map(int, list(input().split(" "))))
1 2 34 567 890
[1, 2, 34, 567, 890]
You can try
[int(e) for e in input().split()]
This is a list comprehension that converts all split string in integers. It will raise an exception if string can not be converted to integers.