2011-12-09 46 views

回答

0

這不是最小巧的功能,但這個會做的伎倆。

string = "Here is my dog" 

def alternateUppercase(s): 
    i = 0 
    a = s.split(' ') 
    l = [] 
    for w in a: 
     if i: 
      l.append(w.upper()) 
     else: 
      l.append(w) 
     i = int(not i) 
    return " ".join(l) 

print alternateUppercase(string) 
+0

非常感謝你,但你可以幫我解釋一下for循環?我對此仍然陌生。 –

+1

@Neal Wang ** a **是a中所有單詞和**的列表,**表示單詞列表中的每個單詞。 for循環爲wordlist(** a **)中的每個單詞(** w **)執行底層代碼。 for循環的一個很好的例子可以在這裏找到(http://www.tutorialspoint.com/python/python_for_loop.htm)。 – enderskill

2

我認爲你正在尋找的方法是upper()。 您可以使用split()你的字符串分割成單詞和其他單詞通話upper()再加入串到一起,使用join()

6
' '.join(w.upper() if i%2 else w 
      for (i, w) in enumerate(sentence.split(' '))) 
+0

像一個真正的簡約;○ – enderskill

1
words = sentence.split(' ') 
sentence = ' '.join(sum(zip(words[::2], map(str.upper, words[1::2])),())) 
+0

這對於使用unicode輸入的python2不起作用(因爲'str.upper')。 – ekhumoro

+0

'lambda x:x.upper()',如果你必須處理'str'和'unicode'。 –

0

使用regex處理任何非字母數字字符的另一種方法。

import re 

text = """The 1862 Derby was memorable due to the large field (34 horses), 
the winner being ridden by a 16-year-old stable boy and Caractacus' 
near disqualification for an underweight jockey and a false start.""" 

def selective_uppercase(word, index): 
    if index%2: 
     return str.upper(word) 
    else: 
     return word 

words, non_words = re.split("\W+", text), re.split("\w+", text) 
print "".join(selective_uppercase(words[i],i) + non_words[i+1] \ 
       for i in xrange(len(words)-1)) 

輸出:

The 1862 Derby WAS memorable DUE to THE large FIELD (34 HORSES), 
the WINNER being RIDDEN by A 16-YEAR-old STABLE boy AND Caractacus' 
NEAR disqualification FOR an UNDERWEIGHT jockey AND a FALSE start. 
相關問題