Python列表.pop()传字符串报错:'str'无法转为整数,求解决方法
错误含义与修复方案
错误含义
TypeError: 'str' object cannot be interpreted as an integer 这个错误的意思很直接:你给list.pop()方法传了字符串参数,但pop()默认只接受整数类型的索引值(也就是元素在列表里的位置序号,从0开始计数),它没法把字符串转换成整数来识别,所以触发了类型错误。
修复方法
Python列表的pop()方法不能直接传元素值,要移除指定元素有两种常用方式:
方式1:用list.remove()直接移除元素值
remove()方法专门用来移除列表中第一个匹配的指定元素,直接传你要删的元素值就行,但要注意字符串区分大小写(比如你的代码里原列表是'Bill',但你写的是'bill',这俩是不同元素,会报错找不到)。
修正后的代码示例:
guests = ['Bill' , 'john' , 'jason' , 'fatima' , 'muhammed' , 'abdul'] print(guests) guests.remove('jason') guests.remove('Bill') # 注意和原列表的大小写保持一致 print(guests) print("Jason could not come because he got sick.") print("Bill could not come because he had to go to a funeral.") print(guests)
方式2:先找索引再用pop()
如果你非要用pop(),可以先通过list.index()获取元素的索引位置,再把索引传给pop()。同样要注意大小写和元素必须存在于列表中:
修正后的代码示例:
guests = ['Bill' , 'john' , 'jason' , 'fatima' , 'muhammed' , 'abdul'] print(guests) guests.pop(guests.index('jason')) guests.pop(guests.index('Bill')) # 匹配原列表的大小写 print(guests) print("Jason could not come because he got sick.") print("Bill could not come because he had to go to a funeral.") print(guests)
补充提醒:不管用哪种方法,如果要移除的元素不在列表里,都会触发
ValueError,如果不确定元素是否存在,可以先通过if 'xxx' in guests:判断后再执行移除操作。
内容的提问来源于stack exchange,提问作者ACertain DeltaruneFan
相关产品推荐
相关产品推荐

