简体   繁体   English

Python 3在一个也包含字母的字符串中添加数字总数

[英]Python 3 add the total of numbers in a string which also contains letters

I have a string like: 我有一个像这样的字符串:

foundstring = 'a1b2c3d4'

And want to add each number for a total like: 并希望将每个数字相加,例如:

1+2+3+4  

So I thought I could use something like making the string to a list and a function using isdigit() to add a running total of the digits in the list like this 所以我想我可以使用将字符串制作到列表中以及使用isdigit()函数在列表中添加连续运行的数字之类的方法

 listset = list(foundstring)
def get_digits_total(list1):
total = 0
for I in list1:
    if I.isdigit():
         total += I

        return total

Which gives you a list like ['a', '1', 'b', '2', 'c', '3', 'd', '4'] But that throws an error 这样会给您一个类似['a', '1', 'b', '2', 'c', '3', 'd', '4']但是会引发错误

unsupported operand type(s) for +=: 'int' and 'str'  

I know there is a very easy way to do this and Im probably making it too complicated. 我知道有一个非常简单的方法可以做到这一点,而我可能会使它过于复杂。 Im trying out some stuff with list comprehension but haven't been able to get isinstance() to do what I want so far 我正在尝试使用列表理解功能,但到目前为止还无法让isinstance()做我想做的事情

Replace 更换

total += i

with

total += int(i)

total is an integer. total是一个整数。 i is a string (always a single character from foundstring ), although one of 0123456789 . i是一个字符串(始终是foundstring的单个字符),尽管是0123456789 In order to "add" it to total , you have to convert it to an integer. 为了将其“加”到total ,您必须将其转换为整数。

'1' + '2' = '12'  # strings
1 + 2 = 3         # integers

As a further inspiration, you can write your get_digits_total as: 作为进一步的启发,您可以将get_digits_total编写为:

total = sum(int(i) for i in foundstring if i.isdigit())

even without converting foundstring to a list, because iterating over a string returns individual characters. 即使不将foundstring转换为列表,也因为迭代字符串会返回单个字符。

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

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