Home > front end >  What does this error mean in Python 3?: TypeError: an integer is required (got type str)
What does this error mean in Python 3?: TypeError: an integer is required (got type str)

Time:03-26

This is my code and I get an error, can u pls help?

codes = input("Codes: ")
separated_codes = codes.split()
for value in separated_codes:
  plain = chr(codes)
  print(plain)

This is my eror:

Traceback (most recent call last):
  File "program.py", line 4, in <module>
    plain = chr(codes)
TypeError: an integer is required (got type str)

CodePudding user response:

Your problem can be demonstrated with a simpler test. input returns a string. In your case its a string of space separated decimal numbers that you split into smaller strings.

>>> codes = "71 39 100 97 121 33"
>>> separated_codes = codes.split()
>>> separated_codes
['71', '39', '100', '97', '121', '33']

We can grab that first string '71' for test

>>> test = separated_codes[0]
>>> test
'71'
>>> chr(test)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required (got type str)

Sure enough, we get the same error.

Help for chr says

chr(i, /)
    Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.

Its job is to convert an ordinal expressed as an integer in the bounds given and return a single character string. We could make that an integer and solve the problem:

>>> chr(int(test))
'G'

You had a list of ordinals, but they were still the characters typed by the user. You need to change them to integers before use.

CodePudding user response:

You're looking for something like this?

codes = input("Codes: ") 
separated_codes = codes.split() 
for value in separated_codes: 
    plain = chr(int(value))
    print(plain)

Input: 99 97 116

Output:c a t

CodePudding user response:

codes = input("Codes: ") separated_codes = codes.split() for value in separated_codes: plain = chr(int(value)) print(plain)

is the answer. You need o aadd an int func but im not sure whhy it is not before the chr(value)

  • Related