简体   繁体   English

如何在字符串中添加输入的数字(Python)

[英]How to add inputed numbers in string.(Python)

How do i add all imputed numbers in a string? 如何在字符串中添加所有估算的数字?

Ex: 例如:

input: 输入:
5 5 3 5 5 5 3 5
output 产量
18 18

and it must supports ('-') 并且必须支持('-')
Ex. 防爆。

input 输入
-5 5 3 5 -5 5 3 5
output 产量
8 8

I write something like this: 我写这样的东西:

x = raw_input()
print sum(map(int,str(x)))

and it adds normally if x>0 如果x> 0,则正常添加
But what to do with ('-') ? 但是如何处理('-')?
I understand that i need to use split() but my knowledge is not enough ( 我了解我需要使用split(),但我的知识还不够(

You're close, you just need to split the string on spaces. 您已经很接近了,只需要将字符串split成空格即可。 Splitting will produce the list of strings ['-5', '5', '3', '5'] . 拆分将生成字符串列表['-5', '5', '3', '5'] Then you can do the rest of the map and sum as you intended. 然后,您可以按照需要完成map的其余部分并sum

>>> 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()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM