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

Python中如何结合使用split与strip函数处理列表元素去除多余空格

问题原因

你之前调用strip()的时机不对,list1.strip()仅会清除整个输入字符串首尾的空白字符,无法处理位于字符串中间、逗号之后的空格,拆分后这些空格就会保留在单个院校名称的开头。

解决方法

拆分字符串后,对拆分得到的每一个院校名称单独执行strip()操作即可,修改后的代码如下:

list1=input("Please write some universities you want to attend, separated by commas, with your first choice first.\n")

# 拆分后对每个元素去除首尾空白
list1 = [item.strip() for item in list1.split(",")]

ranking=range(1,len(list1)+1)
dictionary_of_colleges={rank:school for rank,school in zip(ranking,list1)}
print(dictionary_of_colleges)

测试你给出的输入UPenn, Georgia Tech, Texas, Eastern, NW Missouri State,输出结果为:
{1: 'UPenn', 2: 'Georgia Tech', 3: 'Texas', 4: 'Eastern', 5: 'NW Missouri State'},符合预期。

内容的提问来源于stack exchange,提问作者David KT

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 00:36:07