如何解决 TypeError: 只能连接 str (而不是“ int”)到 str

  • 我决定用 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("")
483586 次浏览

Problem is you are doing the following

str(chr(char + 7429146))

where char is a string. You cannot add a int with a string. this will cause that error

maybe if you want to get the ascii code and add it with a constant number. if so , you can just do ord(char) and add it to a number. but again, chr can take values between 0 and 1114112

Change secret_string += str(chr(char + 7429146))

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

ord() converts the character to its Unicode integer equivalent. chr() then converts this integer into its Unicode character equivalent.

Also, 7429146 is too big of a number, it should be less than 1114111

Python working a bit differently to JavaScript for example, the value you are concatenating needs to be same type, both int or str...

So for example the code below throw an error:

print( "Alireza" + 1980)

like this:

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

To solve the issue, just add str to your number or value like:

print( "Alireza" + str(1980))

And the result as:

Alireza1980

instead of using " + " operator

print( "Alireza" + 1980)

Use comma " , " operator

print( "Alireza" , 1980)

Use this:

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 )

Use f-strings to resolve the 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'
  • The issue may be attempting to evaluate an expression where a variable is the string of a numeric.
  • Convert the string to an int.
  • This scenario is specific to this question
  • When iterating, it's important to be aware of the dtype
i = '15'
# t = 15 + i  # will cause a TypeError


# convert the string to int
t = 15 + int(i)
print(t)


# output
30

Note

  • The preceding part of the answer addresses the TypeError shown in the question title, which is why people seem to be coming to this question.
  • However, this doesn't resolve the issue in relation to the example provided by the OP, which is addressed below.

Original Code Issues

  • TypeError is caused because message type is a str.
  • The code iterates each character and attempts to add char, a str type, to an int
  • That issue can be resolved by converting char to an int
  • As the code is presented, secret_string needs to be initialized with 0 instead of "".
  • The code also results in a ValueError: chr() arg not in range(0x110000) because 7429146 is out of range for chr().
  • Resolved by using a smaller number
  • The output is not a string, as was intended, which leads to the Updated Code in the question.
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

Updated Code Issues

  • message is now an int type, so for char in message: causes TypeError: 'int' object is not iterable
  • message is converted to int to make sure the input is an int.
  • Set the type with str()
  • Only convert value to Unicode with chr
  • Don't use 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 ✑✐✐