Python 如何在用户输入的字符串中添加数字

Python 如何在用户输入的字符串中添加数字,python,string,Python,String,我还在学习Python,遇到了一个问题。我的教授想让我要求用户输入一个有多个数字的数字,而这些数字之间没有任何分隔。然后,他想让我写一个程序,将这些数字相加并打印结果。我不能这样做,因为我不知道怎么做 这就是我正在尝试的: inp = input("Please enter a number with several digits with nothing separating them: ") for number in inp: count += int(len[inp])

我还在学习Python,遇到了一个问题。我的教授想让我要求用户输入一个有多个数字的数字,而这些数字之间没有任何分隔。然后,他想让我写一个程序,将这些数字相加并打印结果。我不能这样做,因为我不知道怎么做

这就是我正在尝试的:

 inp = input("Please enter a number with several digits with nothing separating them: ")
 for number in inp:
       count += int(len[inp])
 print(count)

我尝试过其他方法,但都没用。我做错了什么?我到底该怎么做?这是《Python for Everyone》一书中第6章的内容。

您需要添加
count
变量来存储每个iterable值的总和

在迭代输入字符串并访问for循环中的每个数字时,需要使用
count+=int(list(inp))
而不是
count+=int

inp = input("Please enter a number with several digits with nothing separating them: ")
count = 0
for number in inp:
    count += int(number)
print(count)

你试过那样做吗

inp = input("Please enter a number with several digits with nothing separating them: ")
 count=0
 for number in inp:
     count += int(number)
 print(count)

示例如果用户输入25,结果应该是7,是吗?

首先需要定义
count
变量:

count=0
input()
方法返回一个不带尾随换行符的字符串。您可以对
inp
中的字符进行迭代,将其数值相加:

inp中n的
:
计数+=int(n)

成功了!我意识到了为什么它以前不起作用,因为在我使用变量“count”进行计算之前,我没有为它定义一个值,也没有意识到“number”可以是用户输入的任何值并用于计算。谢谢,我从这里学到了很多。问题是,虽然这个方法有效,但我应该使用函数“len”来访问字符串的长度,然后将字符串中的每个字符添加到另一个字符中。我试过这么做,但没用。我必须使用“len”是因为我的教授要求使用它,而不是因为我这样做了。@AnaBaird您可以使用
作为范围内的索引(len(inp)):count+=int(inp[index])