我正在尝试编写一个函数,它使用 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/