You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

字符串转整数时触发TypeError:'str'对象不支持元素赋值

字符串转整数时触发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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 14:42:40