[英]How to add inputed numbers in string.(Python)
如何在字符串中添加所有估算的數字?
例如:
輸入:
5 5 3 5
產量
18
並且必須支持('-')
防爆。
輸入
-5 5 3 5
產量
8
我寫這樣的東西:
x = raw_input()
print sum(map(int,str(x)))
如果x> 0,則正常添加
但是如何處理('-')?
我了解我需要使用split(),但我的知識還不夠(
您已經很接近了,只需要將字符串split
成空格即可。 拆分將生成字符串列表['-5', '5', '3', '5']
。 然后,您可以按照需要完成map
的其余部分並sum
。
>>> s = '-5 5 3 5'
>>> sum(map(int, s.split()))
8
這很簡單
>>> 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]
然后你想要什么:)
您可以使用以下行:sum(map(int,raw_input()。split()))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.