【问题标题】:Why am I get the error "Can't convert 'int' object to str implicitly"为什么我收到错误“无法将'int'对象隐式转换为str”
【发布时间】:2015-04-12 17:28:04
【问题描述】:

这只是我的程序的一小部分,所以我只是一块一块地创建它。所以我现在要做的就是让我的程序在输入小于或等于 10 时向 ast1 添加一个“*”,但我不断收到错误“无法将'int'对象隐式转换为 str”我不完全确定为什么。有人可以在这里给我一根骨头并帮助我。

ast1 = "*"
count = 0

while (True):
    n = int(input("Enter a number between 0 - 100:"))
    if n<=10:
        ast1 = ast1 + 1 #This is where the error is occuring


print(ast1)

编辑代码:当用户输入“完成”时,如何让该程序终止/中断?

ast1 = ""
ast2 = ""
ast3 = ""
ast4 = ""


while (True):
    n = int(input("Enter a number between 0 - 100:"))
    if n>=0 and n<=25:
        ast1 = ast1 + "*"
    elif n>25 and n<=50:
        ast2 = ast2 + "*"
    elif n>50 and n<=75:
        ast3 = ast3 + "*"
    elif n>75 and n<=100:
        ast4 = ast4 + "*"
    else:break


print(ast1)
print(ast2)
print(ast3)
print(ast4)

【问题讨论】:

    标签: python string int concatenation


    【解决方案1】:

    如果输入小于或等于 10,我现在正在尝试让我的程序在 ast1 中添加一个“*”

    那么你应该这样做:

    ast1 = ast1 + '*'
    

    或者,甚至更短:

    ast1 += '*'
    

    如果你想使用数学运算符,你可以使用乘数:

    # will set ast1 to '**'
    ast1 = ast1 * 2
    

    但是当你第二次做乘法时,你当然会得到'****'。不确定这是否是您想要的。

    你可以直接乘一个星号——比如'*' * 3。它将返回'***'

    【讨论】:

    • 不,这不是我想要的,尽管你确实给了我更多的知识。我正在做的作业是创建一个程序,该程序将输入 0-100 之间的任何数字,直到应用的输入是字符串“done”,然后从那里我将打印每个数字的星号数量 [ 0,25](25,50](50,75](75,100]。但我喜欢分小部分完成作业。
    【解决方案2】:

    这个

    ast1 = ast1 + 1 #This is where the error is occuring
    

    应该是

    ast1 = ast1 + str(1)
    

    数字需要在 Python 中显式类型转换为字符串,尤其是在字符串操作中。

    【讨论】:

      【解决方案3】:

      因为ast1 变量包含*,它被定义为字符串,1 被定义为整数,所以字符串加整数连接是不可能的。不可能对字符串变量和整数变量进行算术运算。

      【讨论】:

      • 因此,如果我想在 ast1 中添加一个“*”,所有输入都是
      • 您的 ast1 变量包含字符串 *。将 int 1 转换为字符串,如 ast1 + str(1)
      猜你喜欢
      • 1970-01-01
      • 2017-12-21
      • 2017-03-27
      • 1970-01-01
      • 2012-11-19
      • 2017-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多