从字符串中获取大写字母

时间:2016-12-30 13:03:33

标签: python string uppercase

我刚刚开始学习python,我只是制作程序来练习我学到的新主题,所以请保持温柔:)

我尝试将var =设为句子,然后检查大写字母,然后将大写字母附加到列表中。如果我更改l = o[6],我会收到'G',因此附加内容.isupper()正在运行,但我似乎无法让i工作,我认为可能是i正在成为一个字符串,但i被声明为一个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)

4 个答案:

答案 0 :(得分:0)

您需要使用循环来构建此列表。在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))

答案 1 :(得分:0)

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

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

print(upperCase)

只需遍历字符串,就可以一次完成一个字母。

答案 2 :(得分:0)

您也可以尝试列表comphresion

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

答案 3 :(得分:0)

作为替代方案,您可以filter使用slc作为:

str.upper
相关问题