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

如何用if条件打印列表中首字母大写姓名并存储小写姓名至新列表

处理姓名列表的两个需求解决方案

1. 打印首字母大写的姓名,同时存储小写首字母的姓名到新列表

基于你提供的while循环代码修改,添加判断逻辑和存储小写首字母姓名的列表:

friends = ["Mohamed", "Shady", "ahmed", "eman", "Sherif"]
lowercase_friends = []  # 用于存储首字母小写的姓名
i = 0
while i < len(friends):
    current_friend = friends[i]
    # 检查姓名首字母是否为大写
    if current_friend[0].isupper():
        print(current_friend)
    else:
        lowercase_friends.append(current_friend)
    i += 1
else:
    print("Done")
    print("首字母小写的姓名列表:", lowercase_friends)

运行后会打印所有首字母大写的姓名,循环结束后输出存储小写首字母姓名的列表。你也可以用current_friend.istitle()替代current_friend[0].isupper(),对于单单词的姓名,两者效果一致。

2. 使用if条件仅打印首字母大写的姓名

在原循环中添加if条件判断,仅当姓名首字母大写时执行打印操作:

friends = ["Mohamed", "Shady", "ahmed", "eman", "Sherif"]
i = 0
while i < len(friends):
    current_friend = friends[i]
    # 仅打印首字母大写的姓名
    if current_friend[0].isupper():
        print(current_friend)
    i += 1
else:
    print("Done")

这段代码会跳过首字母小写的姓名,只输出符合要求的内容。同样,istitle()方法也可以用于这里的判断。

内容的提问来源于stack exchange,提问作者Mahmoud Fathy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:54:24