How do i add all imputed numbers in a string?
Ex:
input:
5 5 3 5
output
18
and it must supports ('-')
Ex.
input
-5 5 3 5
output
8
I write something like this:
x = raw_input()
print sum(map(int,str(x)))
and it adds normally if x>0
But what to do with ('-') ?
I understand that i need to use split() but my knowledge is not enough (
You're close, you just need to split
the string on spaces. Splitting will produce the list of strings ['-5', '5', '3', '5']
. Then you can do the rest of the map
and sum
as you intended.
>>> s = '-5 5 3 5'
>>> sum(map(int, s.split()))
8
its simple
>>> input = raw_input('Enter your input: ')
Enter your input: 5 5 10 -10
>>> list_numbers = [int(item) for item in input.split(' ')]
>>> print list_numbers
[5, 5, 10, -10]
And after what you want :)
您可以使用以下行:sum(map(int,raw_input()。split()))
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.