Python 3 将包含字母的字符串中的数字总数相加
Python 3 add the total of numbers in a string which also contains letters
我有一个像这样的字符串:
foundstring = 'a1b2c3d4'
并希望将每个数字相加得出总数,例如:
1+2+3+4
所以我想我可以使用类似将字符串制作成列表的方法和使用 isdigit() 的函数来添加 运行 列表中的总数字,如下所示
listset = list(foundstring)
def get_digits_total(list1):
total = 0
for I in list1:
if I.isdigit():
total += I
return total
这给你一个像 ['a', '1', 'b', '2', 'c', '3', 'd', '4']
这样的列表
但这会引发错误
unsupported operand type(s) for +=: 'int' and 'str'
我知道有一种非常简单的方法可以做到这一点,我可能把它弄得太复杂了。我正在尝试一些列表理解的东西,但到目前为止 isinstance()
无法做我想做的事
替换
total += i
和
total += int(i)
total
是一个整数。 i
是一个字符串(始终是 foundstring
中的单个字符),尽管是 0123456789
中的一个。为了"add"它到total
,你必须把它转换成一个整数。
'1' + '2' = '12' # strings
1 + 2 = 3 # integers
作为进一步的灵感,您可以将 get_digits_total
写成:
total = sum(int(i) for i in foundstring if i.isdigit())
即使不将 foundstring
转换为列表,因为遍历字符串 returns 个单独的字符。
我有一个像这样的字符串:
foundstring = 'a1b2c3d4'
并希望将每个数字相加得出总数,例如:
1+2+3+4
所以我想我可以使用类似将字符串制作成列表的方法和使用 isdigit() 的函数来添加 运行 列表中的总数字,如下所示
listset = list(foundstring)
def get_digits_total(list1):
total = 0
for I in list1:
if I.isdigit():
total += I
return total
这给你一个像 ['a', '1', 'b', '2', 'c', '3', 'd', '4']
这样的列表
但这会引发错误
unsupported operand type(s) for +=: 'int' and 'str'
我知道有一种非常简单的方法可以做到这一点,我可能把它弄得太复杂了。我正在尝试一些列表理解的东西,但到目前为止 isinstance()
无法做我想做的事
替换
total += i
和
total += int(i)
total
是一个整数。 i
是一个字符串(始终是 foundstring
中的单个字符),尽管是 0123456789
中的一个。为了"add"它到total
,你必须把它转换成一个整数。
'1' + '2' = '12' # strings
1 + 2 = 3 # integers
作为进一步的灵感,您可以将 get_digits_total
写成:
total = sum(int(i) for i in foundstring if i.isdigit())
即使不将 foundstring
转换为列表,因为遍历字符串 returns 个单独的字符。