Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python在字符串中添加整数_Python - Fatal编程技术网

Python在字符串中添加整数

Python在字符串中添加整数,python,Python,我得到了一个错误: >>> sum_digits(123) Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> sum_digits(123) File "D:/Python/Final/#4.py", line 4, in sum_digits for i in n: TypeError: 'int' object is not

我得到了一个错误:

>>> sum_digits(123)
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    sum_digits(123)
  File "D:/Python/Final/#4.py", line 4, in sum_digits
    for i in n:
TypeError: 'int' object is not iterable
>>> 

您需要将数字转换为
str
(而不是
int
)并进行迭代:

def sum_digits(n):
   s = 0
   for i in str(n):
      s += int(i)
   return s
用法:

>>> sum_digits(123)
6
使用和:


如果希望
i
的范围超过
n
的位数,则需要如下内容:

for i in [int(x) for x in str(n)]:

或者,你可以直接将
“123”
而不是
123
传递到
sum\u digits
,你的文章标题表明这就是你真正想要做的。当然,您需要将每个字符转换为其数值。

这里的问题是,您正在向函数传递一个
int
,而您无法对其进行迭代

我建议解决办法

>>> n = 123
>>> sum(int(x) for x in str(n))
6

不能对int进行迭代,但仍可以在不强制转换为
str的情况下进行迭代:

def sum_digits(n):
    n, i = divmod(n, 10)
    while n:
        n, r = divmod(n, 10)
        i += r
    return i
演示:


从int到str再转换回int没有多大意义。

显示完整的回溯。顺便说一句,错误消息和代码不匹配:
对于int(n)中的i
对于n中的i
sum_digits(123)回溯(最后一次调用):文件“”,第1行,sum_digits(123)文件“D:/Python/Final/#4.py”,第4行,在n:TypeError中的i的sum_数字中:“int”对象是不可编辑的>>>即使这是一个很好的一行,否则我会反对,这个人似乎是一个初学者,只是在尝试这种语言。这种语法似乎不熟悉。
>>> n = 123
>>> sum(int(x) for x in str(n))
6
def sum_digits(n):
    n, i = divmod(n, 10)
    while n:
        n, r = divmod(n, 10)
        i += r
    return i
In [2]:  sum_digits(123456789)
Out[2]: 45

In [3]:  sum_digits(123)
Out[3]: 6

In [4]:  sum_digits(100)
Out[4]: 1