Dec-04-2020, 10:02 AM
Dec-04-2020, 10:31 AM
The
If you have this list with strings:
Some examples:
""
format you mean, is a str
.If you have this list with strings:
some_values = ["1", "-5", "10", "-15"]You can cast the
str
to int
with different methods.Some examples:
# the values defined here some_values = ["1", "-5", "10", "-15"] # list comprehension new_some_values_1 = [int(value) for value in some_values] # classical for-loop new_some_values_2 = [] # empty list for value in some_values: value = int(value) new_some_values_2.append(value) # functional style with map # each element of some_values is called with int() # the list consumes the resulting map object # it's lazy evaluated, not consuming the map object -> no values new_some_values_3 = list(map(int, some_values)) # generator expression + for-loop values = (int(value) for value in some_values) for value in values: # <- evaluation of the generator begins here print(value, type(value)) # <- printing the value and type of value # now values is consumed # you can't use it again because it's now empty
Dec-04-2020, 10:44 AM
But what I'm talking about is that the user types the numbers in 1 line:
3 5 7 2 53 2
and not:
23
5
7
2
53
2
I have it like this now:
t.extend(input().split())
3 5 7 2 53 2
and not:
23
5
7
2
53
2
I have it like this now:
t.extend(input().split())
Dec-04-2020, 11:05 AM
One way is to use list comprehension:
>>> data = input('Enter number separated by space: ') Enter number separated by space: 23 4 5 6 7 >>> [int(entry) for entry in data.split()] [23, 4, 5, 6, 7]
Dec-04-2020, 12:29 PM
(Dec-04-2020, 10:44 AM)1234 Wrote: [ -> ]But what I'm talking about is that the user types the numbers in 1 line
The solution provided perfringo.
The only problem is the user itself. The user could make mistakes during entering the numbers.
If there is for example one accidental comma in the user-input, int(entry) will raise a ValueError.
Just saying, don't trust users input.