Python新手在Grok Learning课程中遭遇整数字符串转字符失败及AttributeError错误求助
Fixing the AttributeError: 'int' has no attribute 'split'
Hey there! Let's break down what's going wrong with your code and get it working properly.
What's Causing the Error?
The key mistake is in your first line: you're converting the user's input directly to an int with values = int(input("Codes: ")). But integers don't have a split() method—split() is a string-only function! When you try to call values.split() later, Python throws an error because it can't use a string method on a numeric type.
The Corrected Code
Here's how to adjust your code to convert integer codes to their corresponding characters successfully:
# Capture input as a string first (don't convert to int immediately) values_input = input("Codes: ") # Split the input string into individual code strings separated_values = values_input.split() # Loop through each code string, convert to int, then to a character for code_str in separated_values: code = int(code_str) print(chr(code))
How This Works
- Keep input as a string: We first grab the user's input as raw text, which lets us use
split()to break it into separate code parts (e.g., input"65 66 67"becomes["65", "66", "67"]). - Convert each part to integer: For each string in the split list, we convert it to an integer—this is what
chr()requires to turn an ASCII code into a character. - Generate the character:
chr(code)takes the integer code and returns its matching ASCII character (e.g.,chr(65)outputs"A").
Example Test Run
If you input 65 66 67, the code will output:
A B C
内容的提问来源于stack exchange,提问作者Myth Rhythm
相关产品推荐
相关产品推荐

