zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python列表之for循环应用

2023-09-14 09:15:42 时间

一、程序要求及目的

将列表中姓张的人名元素改为姓李的,使用for循环

二、代码内容

# 列表在for循环中使用
lst = ["张飞", "赵云", "徐晃", "于禁", "张辽", "王平"]
for i in range(len(lst)):
    item = lst[i]
    if item.startswith("张"):
        new_name = "李"+item[1:]
        print(new_name)
        lst[i] = new_name

print(lst)

三、代码运行

D:\soft\python\python.exe D:/soft/pycharm/pycharmfile/py基础/02_python基础类型/10_列表的应用.py
李飞
李辽
['李飞', '赵云', '徐晃', '于禁', '李辽', '王平']

Process finished with exit code 0