字符串转整数时触发TypeError:'str'对象不支持元素赋值
Hey there, let's break down what's causing that error and fix it up!
First, let's get to the root of the problem: In your final for loop, you're trying to modify individual characters of the values variable with values[i] = int(values[i])—but values is a string, and strings in Python are immutable. That means you can't change their characters directly like this, which is exactly why you're seeing the TypeError: 'str' object does not support item assignment message.
Luckily, you're already halfway to the solution! You split values into values_list, which is a list of the number strings you care about (like ['9', '223', '372', ...]). This list is the right object to work with, not the original string.
Here's the corrected version of your code, with two common ways to convert those strings to integers:
Option 1: Use a list comprehension (clean and concise)
generate_list = [ "9", " ", "2", "2", "3", " ", "3", "7", "2", " ", "3", "6", " ", "8", "5", "4", " ", "7", "7", "5", " ", "8", "0", "7", " ", ] values = "".join(generate_list) print(values) # 输出: 9 223 372 36 854 775 807 values_list = values.split() print(values_list) # 输出: ['9', '223', '372', '36', '854', '775', '807'] # 将values_list中的每个字符串转成整数 int_values = [int(item) for item in values_list] print(int_values) # 输出: [9, 223, 372, 36, 854, 775, 807]
Option 2: Use a traditional for loop (if you prefer explicit iteration)
generate_list = [ "9", " ", "2", "2", "3", " ", "3", "7", "2", " ", "3", "6", " ", "8", "5", "4", " ", "7", "7", "5", " ", "8", "0", "7", " ", ] values = "".join(generate_list) print(values) values_list = values.split() print(values_list) int_values = [] for item in values_list: int_values.append(int(item)) print(int_values)
The key takeaway here is: Always remember that strings in Python can't be modified in-place. Instead, work with mutable structures like lists when you need to transform individual elements.
备注:内容来源于stack exchange,提问作者Catt FoXxY

