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

Python列表insert方法返回None问题求助:终端正常但程序异常

问题根源分析

你的问题出在对列表insert()方法的理解上——list.insert()是原地修改列表,它的返回值是None。当你执行st=st.insert(position,salt_value)时,相当于把None赋值给了st,所以最后打印st会输出None。

修正方案

只需要去掉赋值操作,直接调用insert()方法修改原列表即可。另外还要补充一个小细节:当position > len(get_string)时,你只打印了exit但没有终止程序,后续操作可能会引发索引错误,建议加上exit()或者调整逻辑。

修正后的完整代码

from random import shuffle
value=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0']
get_string=input('Enter the string:- ')
try:
    position=int(input('Enter the Salt position:- '))
    salt_length=int(input('Enter the length of the salt:- '))
except ValueError:
    print ('Error:- Deserve a "integer" number.')  # 顺便修正拼写错误
    exit()
shuffle(value)
value=",".join(value)
value="".join(value.split(',',salt_length-1))
salt_value=value.split(',')[0]
print(salt_value)
if position > len(get_string):
    print('exit')
    exit()  # 新增:超出位置时终止程序,避免后续报错
get_string=get_string.strip()
st=list(get_string)
print(st)
# 去掉赋值,直接调用insert修改原列表
st.insert(position,salt_value)
print(st)
关键知识点补充
  • 列表的原地修改方法(比如insert()、append()、sort()、reverse()等)都不会返回修改后的列表,而是返回None,它们直接修改原对象。
  • 如果需要保留原列表并得到修改后的新列表,可以用切片拼接的方式,比如:new_st = st[:position] + [salt_value] + st[position:],这种方式会返回新列表,原列表不受影响。

内容的提问来源于stack exchange,提问作者Anirban Singha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:16:10