【问题标题】:How to resolve TypeError: can only concatenate str (not "int") to str [duplicate]如何解决TypeError:只能将str(不是“int”)连接到str [重复]
【发布时间】:2018-12-17 13:16:06
【问题描述】:
  • 我决定制作某种密码用于测试 Unicode。
  • 我已经通过在 Unicode 中添加数字来做到这一点,所以这将是一种秘密。
  • 我一直收到此错误,但我不知道如何解决。
    • 有什么解决办法吗?

原码

message = input("Enter a message you want to be revealed: ")
secret_string = ""
for char in message:
    secret_string += str(chr(char + 7429146))
print("Revealed", secret_string)
q = input("")

原始错误

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-182-49ece294a581> in <module>
      2 secret_string = ""
      3 for char in message:
----> 4     secret_string += str(chr(char + 7429146))
      5 print("Revealed", secret_string)
      6 q = input("")

TypeError: can only concatenate str (not "int") to str

更新代码

while True:
    try:
        message = int(input("Enter a message you want to be decrypt: "))
        break
    except ValueError:
        print("Error, it must be an integer")
secret_string = ""
for char in message:
    secret_string += chr(ord(char - str(742146)))
print("Decrypted", secret_string)
q = input("")

【问题讨论】:

    标签: python unicode


    【解决方案1】:

    问题是您正在执行以下操作

    str(chr(char + 7429146))
    

    其中 char 是一个字符串。您不能添加带有字符串的 int。这将导致该错误

    如果您想获取 ascii 代码并添加一个常数,也许可以。如果是这样,您可以执行 ord(char) 并将其添加到数字中。但同样,chr 可以取 0 到 1114112 之间的值

    【讨论】:

      【解决方案2】:

      更改secret_string += str(chr(char + 7429146))

      secret_string += chr(ord(char) + 7429146)

      ord() 将字符转换为其等效的 Unicode 整数。 chr() 然后将此整数转换为其等效的 Unicode 字符。

      另外,7429146这个数字太大了,应该小于1114111

      【讨论】:

        【解决方案3】:

        Python 的工作方式与 JavaScript 有点不同,例如,您要连接的值必须是相同的类型,intstr。 ..

        例如下面的代码抛出错误

        print( "Alireza" + 1980)
        

        像这样:

        Traceback (most recent call last):
          File "<pyshell#12>", line 1, in <module>
            print( "Alireza" + 1980)
        TypeError: can only concatenate str (not "int") to str
        

        要解决此问题,只需将 str 添加到您的数字或值中,例如:

        print( "Alireza" + str(1980))
        

        结果为:

        Alireza1980
        

        【讨论】:

          【解决方案4】:

          而不是使用“+”运算符

          print( "Alireza" + 1980)
          

          使用逗号“,”运算符

          print( "Alireza" , 1980)
          

          【讨论】:

          • print( "Alireza" , 1980) 输出 Alireza 1980 之间有一个额外的空格。
          • 为了避免多余的空间,可以覆盖sep 参数的默认值:print("Alireza" , 1980, sep='')
          • 这仅适用于print,因为它需要无限数量的参数来打印。它在尝试将字符串与整数连接的一般情况下不起作用。
          【解决方案5】:

          使用这个:

          print("Program for calculating sum")
          numbers=[1, 2, 3, 4, 5, 6, 7, 8]
          sum=0
          for number in numbers:
              sum += number
          print("Total Sum is: %d" %sum )
          

          【讨论】:

            【解决方案6】:

            使用 f 字符串解析 TypeError

            # the following line causes a TypeError
            # test = 'Here is a test that can be run' + 15 + 'times'
            
            # same intent with a f-string
            i = 15
            
            test = f'Here is a test that can be run {i} times'
            
            print(test)
            
            # output
            'Here is a test that can be run 15 times'
            
            i = 15
            # t = 'test' + i  # will cause a TypeError
            
            # should be
            t = f'test{i}'
            
            print(t)
            
            # output
            'test15'
            
            • 问题可能是试图计算一个变量是数字字符串的表达式。
            • 将字符串转换为int
            • 这个场景是针对这个问题的
            • 迭代时,注意dtype 很重要
            i = '15'
            # t = 15 + i  # will cause a TypeError
            
            # convert the string to int
            t = 15 + int(i)
            print(t)
            
            # output
            30
            

            注意

            • 答案的前一部分解决了问题标题中显示的TypeError,这就是人们似乎提出这个问题的原因。
            • 但是,这并不能解决与 OP 提供的示例相关的问题,该问题将在下面解决。

            原始代码问题

            • TypeError 是因为message 类型是str 造成的。
            • 代码迭代每个字符并尝试将charstr 类型)添加到int
            • 可以通过将char 转换为int 来解决该问题
            • 在呈现代码时,secret_string 需要使用0 而不是"" 进行初始化。
            • 该代码还会生成 ValueError: chr() arg not in range(0x110000),因为 7429146 超出了 chr() 的范围。
            • 已通过使用较小的数字解决
            • 输出不是预期的字符串,这会导致问题中的更新代码。
            message = input("Enter a message you want to be revealed: ")
            
            secret_string = 0
            
            for char in message:
                char = int(char)
                value = char + 742146
                secret_string += ord(chr(value))
                
            print(f'\nRevealed: {secret_string}')
            
            # Output
            Enter a message you want to be revealed:  999
            
            Revealed: 2226465
            

            更新的代码问题

            • message 现在是 int 类型,所以 for char in message: 导致 TypeError: 'int' object is not iterable
            • message 转换为 int 以确保 inputint
            • str()设置类型
            • 仅使用chrvalue 转换为Unicode
            • 不要使用ord
            while True:
                try:
                    message = str(int(input("Enter a message you want to be decrypt: ")))
                    break
                except ValueError:
                    print("Error, it must be an integer")
                    
            secret_string = ""
            for char in message:
                
                value = int(char) + 10000
                
                secret_string += chr(value)
            
            print("Decrypted", secret_string)
            
            # output
            Enter a message you want to be decrypt:  999
            Decrypted ✙✙✙
            
            Enter a message you want to be decrypt:  100
            Decrypted ✑✐✐
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2021-02-15
              • 1970-01-01
              • 2020-10-06
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多