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 ???