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

函数内Return与Print用法:如何让函数返回所有大写字母

解决返回字符串所有大写字母的函数问题

你遇到的问题根源在于:

  • 函数内部用print输出时,调用函数会直接打印内容,再用print包裹函数调用会额外打印函数的返回值None,导致重复输出。
  • 循环里直接用return会终止函数执行,所以只能返回第一个找到的大写字母。

正确的做法是先收集所有符合条件的大写字母,最后统一返回这个结果,具体有两种实现方式:

方式一:字符串拼接收集

def get_capitals(string):
    capitals = ""
    for char in string:
        # 用isupper()判断大写字母,比ord范围更直观
        if char.isupper():
            capitals += char
    return capitals

# 调用示例
print(get_capitals("CS1301"))  # 输出 CS
print(get_capitals("Georgia Institute of Technology"))  # 输出 GIT

方式二:列表推导式简化代码

def get_capitals(string):
    # 用列表推导式筛选大写字母,再join成字符串返回
    return ''.join([char for char in string if char.isupper()])

# 调用示例
print(get_capitals("CS1301"))
print(get_capitals("Georgia Institute of Technology"))

补充说明:

  • 原代码中的try-except没有必要,因为字符串的每个字符都可以正常调用ord(),不需要异常捕获。
  • 优先使用str.isupper()方法判断大写字母,代码可读性更高,也能覆盖所有Unicode大写字符(不止ASCII的A-Z)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 20:02:40