python - Python3.3.5如何在字符串中添加数字和字母(最终结果应该是int)?

标签 python string integer

我的任务是:

“编写一个函数 sumOfDigits,它有一个字符串类型的参数。该函数应该返回 字符串中数字的总和。不要将多位字符串视为一个数字——“2014”应该是 被视为 2、0、1、4 的 4 个不同数字。该函数应为字符串“今天的日期”返回 17 是 09/01/2014”。您可以假设参数是一个字符串。无需进行任何类型验证。”

这是我到目前为止所得到的(有适当的缩进):

def sumOfDigits (string1: str):

   summation=0

   for i in string1:
        summation=summation + int (i)

   return (summation) 

print (sumOfDigits ('543tf'))

我收到以下错误:

"Traceback (most recent call last):

  File "C:\Users\Andrew\Desktop\lab3.py", line 45, in <module>

    print (sumOfDigits ('543tf'))

  File "C:\Users\Andrew\Desktop\lab3.py", line 42, in sumOfDigits

    summation=summation + int (i)

ValueError: invalid literal for int() with base 10: 't'"

我该如何解决这个问题?这样做是因为添加 int 和 string/char 的困难吗?

最佳答案

问题是 int(x) 失败,除非 x 是数字。解决方案是仅对数字求和。为此,python 有字符串方法isdigit。例如:

>>> s = '543tf'
>>> sum(int(x) for x in s if x.isdigit())
12

和:

>>> s = "Today’s date is 09/01/2014"
>>> sum(int(x) for x in s if x.isdigit())
17

Python3

Unicode 添加了大量字符,python 将其中一些归类为数字,即使 int 不接受它们。一个这样的例子是上标 3:³。为了解决这个问题,python3 引入了 isdecimal 并使其比 isdigit 更具辨别力。因此,在 python3 中,可以使用:

>>> s = "Today’s date is 09/01/2014 See footnote³"
>>> sum(int(x) for x in s if x.isdecimal())
17

关于python - Python3.3.5如何在字符串中添加数字和字母(最终结果应该是int)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26309974/

相关文章:

mysql - 非常大的整数插入 MySQL 中的 "TEXT"类型列

python - 使用 Python 连接 CSV 中的行

C# 字符串 - 简单语法问题

java - java中格式化字符串

c# - 将空值传递给 int?

arrays - 如何找到字符串数组中的最小元素,但只考虑整数?

python - Django Pyinstaller .EXE 给我 ModuleNotFoundError : No module named 'app.urls'

python - 为什么我的第二个函数没有返回任何内容?

Python,字典到 CSV : is there a faster way to do it?

java - 替换字符串中特定索引处的字符?