如何解决TypeError: can only concatenate str (not "int") to str错误

115
  • 我决定用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("")
6个回答

162

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
为了解决这个问题,只需将字符串添加到您的数字或值中,例如:

要解决此问题,请将字符串添加到您的数字或值中,例如:

print( "Alireza" + str(1980))

结果为:

Alireza1980

31

使用 f-strings 解决 TypeError

# the following line causes a TypeError
# test = 'Here is a test that can be run' + 15 + 'times'

# same intent with an 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
    • 该场景仅适用于此问题。
  • 在迭代时,了解类型非常重要。
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 的原因是 type(message) → str
    • 代码迭代每个字符并尝试将char添加到一个int,其中charstr类型。
    • 可以通过将char转换为int来解决该问题。
    • 按照代码的表示方式,需要使用0而不是""来初始化secret_string
  • 该代码还导致了 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,以确保 input 是一个 int
    • 使用 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 ✑✐✐

21

使用“ + ”运算符的替代方法

print( "Alireza" + 1980)
使用逗号 " , " 操作符。
print( "Alireza" , 1980)

print("Alireza", 1980) 输出 Alireza 1980,中间有一个额外的空格。 - stomtech
4
为了避免额外的空格,可以覆盖sep参数的默认值:print("Alireza" , 1980, sep='') - Tomerikoo
1
这仅适用于 print,因为它可以打印无限数量的参数。在尝试将字符串与整数连接起来的一般情况下,它不起作用。 - Flimm

4

使用此代码:

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 )

3
问题在于您正在执行以下操作:
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。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接