5 回答

TA贡献1853条经验 获得超18个赞
例如,Python的工作方式与JavaScript有所不同,您要连接的值必须是int或str相同的类型。
因此,例如下面的代码抛出错误:
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

TA贡献1804条经验 获得超2个赞
使用f字符串来解决 TypeError
f字符串:一种在Python中格式化字符串的新方法和改进方法
PEP 498-文字字符串插值
# 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是由于messagetype是造成的str。
该代码会迭代每个字符,并尝试将char,str类型和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以确保input是int。
用 str()
仅value使用chr
不要使用 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 ✑✐✐

TA贡献1806条经验 获得超5个赞
改变 secret_string += str(chr(char + 7429146))
至 secret_string += chr(ord(char) + 7429146)
ord()
将字符转换为其等效的Unicode整数。chr()
然后将此整数转换为等效的Unicode字符。
另外,7429146的个数太大,应小于1114111

TA贡献1835条经验 获得超7个赞
用这个:
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 )
添加回答
举报