【问题标题】:Getting just the upper case letters from a string仅从字符串中获取大写字母
【发布时间】:2016-12-30 13:03:33
【问题描述】:

我刚刚开始学习python,我只是在编写程序来练习我所学的新主题,所以请温柔:)

我尝试在一个句子中添加一个 var =,然后检查大写字母,然后将大写字母附加到一个列表中。如果我改变l = o[6] 我得到'G' 所以追加和.isupper() 工作但我似乎无法让i 工作,我认为它可能是i 正在变成一个字符串但@987654326 @ 被声明为一个 int (python 3.6)。

这是我目前所拥有的:

o = "the doG jUmPeD ovEr The MOOn"
upperCase = []
i = 0
l = o[i]

if l.isupper() == True:
   upperCase.append(l)

else:
    i += 1

print (upperCase)

【问题讨论】:

  • 你需要使用循环
  • 我认为您需要花一些时间在official Python tutorial 上。这是一个很棒的教程。
  • 我投票决定将此问题作为离题结束,因为 SO 不是教程服务。
  • 谢谢你的提示,我只是把我学到的一些东西放在一起,看看我是否理解我学到的东西。
  • 一些文本清理,突出显示文本中的变量,添加uppercase标签表示.usupper()检查。

标签: python string uppercase


【解决方案1】:

你可以更简单地做到这一点。

o = "the doG jUmPeD ovEr The MOOn"
upperCase = []
for letter in o:
    if letter.isupper():
        upperCase.append(letter)

print(upperCase)

只需遍历字符串,它会一次一个字母。

【讨论】:

    【解决方案2】:

    你也可以试试列表合成

    upperCase= [ i for i in o if i.isupper() ]
    

    【讨论】:

    • 这将得到一个列表的结果。您应该使用''.join(i for i in o if i.isupper()) 来获取字符串。
    【解决方案3】:

    作为替代方案,您可以使用 filterstr.upper 作为:

    >>> o = "the doG jUmPeD ovEr The MOOn"
    
    # Python 2
    >>> filter(str.isupper, o)
    'GUPDETMOO'
    
    # Python 3
    >>> ''.join(filter(str.isupper, o))
    'GUPDETMOO'
    

    【讨论】:

    • 不错。没想到这个
    【解决方案4】:

    您需要使用循环来构建此列表。在 Python 中构建 for 循环非常简单。它只是一个一个地遍历所有字母。尝试将代码修改为,

    o = "the doG jUmPeD ovEr The MOOn"
    upperCase = []
    for i in range(0, len(o)):
        l = o[i]  
        if l.isupper() == True:
           upperCase.append(l)
    
    print (upperCase)
    

    当然,还有更好的方法来做到这一点。您不需要明确定义l = o[i]。您可以将其作为循环的一部分!此外,您不需要== True。像这样 -

    o = "the doG jUmPeD ovEr The MOOn"
    upperCase = []
    for l in o:
        if l.isupper():
           upperCase.append(l)
    
    print (upperCase)
    

    更好的是,使用filterlambda

    print(filter(lambda l: l.isupper(), o))
    

    【讨论】:

    • 我知道你试图向 OP 展示他们做错了什么,但你真的不应该使用 range(len(whatever)) - 他们不妨从一开始就学习用 Python 编写东西.此外,无需预先初始化 i,或与 True 进行显式比较。
    • 我添加了一个新的实现,并添加了另一种pythonic方式
    • 你为什么要l.isupper() == Truel.isupper() 已经计算为布尔值。
    • 感谢您的快速回复和感谢。
    • @Ashley 如果您满意,请接受答案
    猜你喜欢
    • 2021-09-12
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 2021-01-06
    • 2012-02-17
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多