python - 如何使用 isupper( ) 方法在 Python 中只打印大写字母?

标签 python string python-2.7

我正在尝试编写一个函数,它使用 for 循环和 isupper 方法来仅打印字符串的大写字母。

到目前为止我做了什么:

upper_chars = ""
def only_upper(s):
    for char in s:
        if s.isupper() == True:
        upper_chars += char
 print upper_chars

但这不起作用?谁能告诉我为什么? 我收到此错误消息:“UnboundLocalError:赋值前引用了局部变量‘upper_chars’”

最佳答案

代码中的几个问题:

  • 你应该在函数内部定义upper_chars变量
  • 在循环中你应该对一个字符调用isupper(),而不是整个字符串
  • 你的函数应该返回一些东西
  • 你应该调用函数
  • if block 中的缩进错误

这是修复后的代码:

def only_upper(s):
    upper_chars = ""
    for char in s:
        if char.isupper():
            upper_chars += char
    return upper_chars

print only_upper("HeLLo WorLD")

此外,您还可以使用 filter():

def only_upper(s):
    return filter(lambda x: x.isupper(), s)

print only_upper("HeLLo WorLD")

或者:

def only_upper(s):
    return "".join(c for c in s if c.isupper())

print only_upper("HeLLo WorLD")

同时打印:

HLLWLD

关于python - 如何使用 isupper( ) 方法在 Python 中只打印大写字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22585379/

相关文章:

python - 键盘中断程序不返回值

python - Bokeh:在单个 Python 回调中多次更新图形

python - 并发.futures:确定哪个 future 返回

c - 在 C 中删除 URL 中的单点路径名

python - 请求的地址在其上下文错误中无效

python 2.7 写 "x in set"与 "set.__contains__(x)"

python - Django:扩展查询集/使用 OR 连接多个过滤器

C++ 将 const char * 与字符串连接,仅打印 const char *

复制结构体数组元素中的字符串

Python代码仅适用于标题标签,不适用于表格