2016-12-30 82 views
-1

我剛開始學習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) 
+1

你需要使用一個循環 – martianwars

+1

我認爲你需要花費一些與[官方Python教程](https://docs.python.org/3.6/tutorial/index.html)。這是一個很棒的教程。 – TigerhawkT3

+1

我投票結束這個問題作爲題外話,因爲這不是一個教程服務。 – TigerhawkT3

回答

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

我知道你試圖向OP展示他們做錯了什麼,但你真的不應該使用範圍(len(無論)) - 他們不妨學會從一開始就用Python來寫東西。另外,不需要預先初始化i,或者與True進行明確比較。 –

+1

我添加了一個新的實現,並添加了一個pythonic方法 – martianwars

+0

你爲什麼要做'l.isupper()== True'? 'l.isupper()'已經評估爲一個布爾值。 – TigerhawkT3

0

你可以做到這一點更簡單。

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

print(upperCase) 

只需迭代字符串,它一次只能做一個字母。

0

您也可以嘗試列表comphresion

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

作爲替代方案,str.upper,你可以使用filter有:

>>> o = "the doG jUmPeD ovEr The MOOn" 

# Python 2 
>>> filter(str.isupper, o) 
'GUPDETMOO' 

# Python 3 
>>> ''.join(filter(str.isupper, o)) 
'GUPDETMOO' 
+0

不錯。沒想過這個 – NinjaGaiden