python - 困惑为什么我不能将字符串添加在一起

标签 python accumulator

我正在尝试编写一个程序来获取用户信息并将其添加到列表中,然后我想计算总共有多少用户输入,但我做不到。我尝试运行累加器,但收到 TypeError: unsupported operand type(s) for +: 'int' and 'str'。

def main():
    #total = 0

    cel_list = []

    another_celeb = 'y'

    while another_celeb == 'y' or another_celeb == 'Y':

        celeb = input('Enter a favorite celebrity: ')

        cel_list.append(celeb)

        print('Would you like to add another celebrity?')

        another_celeb = input('y = yes, done = no: ')


        print()
    print('These are the celebrities you added to the list:')
    for celeb in cel_list:
        print(celeb)
        #total = total + celeb
        #print('The number of celebrities you have added is:', total)



main() 

这是不带累加器的所需输出,但我仍然需要将输入相加。我已经注释掉了累加器。

Enter a favorite celebrity: Brad Pitt
Would you like to add another celebrity?
y = yes, done = no: y

Enter a favorite celebrity: Jennifer Anniston
Would you like to add another celebrity?
y = yes, done = no: done

These are the celebrities you added to the list:
Brad Pitt
Jennifer Anniston
>>> 

预先感谢您的任何建议。

最佳答案

Total 是一个整数(之前声明为)

    total = 0

正如错误代码所示,您正在尝试将整数与字符串连接起来。这是不允许的。要解决此错误,您可以:

    ## convert total from int to str
    output = str(total) + celeb
    print(" the number of celebrities you have added is', output)

或者更好的是,您可以尝试使用字符串格式

    ##output = str(total) + celeb
    ## using string formatting instead
    print(" the number of celebrities you have added is %s %s', %  (total, celeb))

我希望这对你有用

关于python - 困惑为什么我不能将字符串添加在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24644212/

相关文章:

python - 我如何才能等到使用 Python 套接字接收数据?

python - 使用 Pandas GroupBy 找到每个组的一半

python - 图像拟合和插值

list - Java 8 - 积累和创建新的集合

c - C中计算任意函数1到10的函数

haskell - 无可辩驳的模式不会在递归中泄漏内存,但为什么呢?

python - 我怎样才能用pyqt在qtableview中显示一个矩阵

python - 将 n 个参数传递给 Python 中的函数

f# - F# 中的累加器生成器

scala - Spark accumulableCollection 不适用于 mutable.Map