简体   繁体   English

如何在没有空格的数字串中添加每个数字

[英]How to add each digit in a string of numbers with no spaces

Im currently trying to take a sequence of numbers in a string input, and then convert those numbers into a total to print.我目前正在尝试在字符串输入中获取一系列数字,然后将这些数字转换为要打印的总数。 In concept this should be easy, but I'm having trouble figuring it out.从概念上讲,这应该很容易,但我无法弄清楚。 I've searched Stack but could not find a solution that fits my current problem.我搜索了 Stack,但找不到适合我当前问题的解决方案。

This is my current progress:这是我目前的进展:

def main():
numbers= input("Enter a sequence of numbers with no spaces:")
numbers= list(numbers)
total= ""
for i in numbers:
    total= total + i

print(total)

main()主要的()

My logic is to break the sequence of numbers into a list, then add the numbers in a loop, to then produce the total.我的逻辑是将数字序列分成一个列表,然后在循环中添加数字,然后生成总数。 Unfortunately this only returns the original string, so I decided to put:不幸的是,这只返回原始字符串,所以我决定放:

for i in numbers:对于我的数字:

i= eval(i)
total= total + i

and

for i in numbers:对于我的数字:

i= int(i)
total= total + i

This returns an error stating that i needs to be a string, but this will only lead to another concatenation.这将返回一个错误,指出 i 需要是一个字符串,但这只会导致另一个连接。

Does anyone know how to produce what I'm looking for?有谁知道如何生产我正在寻找的东西? ie "1234" = 10.即“1234”= 10。

The string itself is an iterable, so you can iterate over it and convert each character to an int and then use sum to add them.字符串本身是可迭代的,因此您可以对其进行迭代并将每个字符转换为 int,然后使用 sum 将它们相加。

>>> numbers= input("Enter a sequence of numbers with no spaces:")
Enter a sequence of numbers with no spaces:1234567
>>> sum([int(i) for i in numbers])
28

or lose the outer [] to make it a generator expression.或丢失外部[]以使其成为生成器表达式。 It will work either way, however for a small input like this arguably the generator overhead might exceed its benefits in terms of memory usage.无论哪种方式它都可以工作,但是对于像这样的小输入,可以说生成器的开销可能会超过其在内存使用方面的好处。

There's no need to turn the string into a list, since it's already an iterable.无需将字符串转换为列表,因为它已经是可迭代的。 Instead, just do something like this:相反,只需执行以下操作:

numbers = input(‘Enter numbers: ‘)
total = 0

for char in numbers:
    total += int(char)

print(total)

This goes through each character in the string, turns it into an integer, and adds it to the total.这会遍历字符串中的每个字符,将其转换为整数,并将其添加到总数中。

Just to add one more answer here.只是在这里添加一个答案。 If your string that you are accepting is comma seperated, then here is a one liner if it is python 2.7如果您接受的字符串是逗号分隔的,那么如果它是 python 2.7,那么这里是一个单行

 sequence = map(int, input().split(','))

else for python3,否则为python3,

sequence = list(map(int, input().split(',')))

I hope it adds something to already given answers.我希望它能为已经给出的答案添加一些东西。

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

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