2016-09-07 44 views
2
#!/usr/bin/python 
# -*- coding: utf-8 -*- 
def to_weird_case(string): 
    lines = string.split() 
    new_word = '' 
    new_line = '' 
    for word in lines: 
     for item in word: 
      if word.index(item) %2 ==0: 
       item = item.upper() 
       new_word += item 
      else: 
       new_word += item 
     new_line = new_word +' ' 
    return new_line 
print to_weird_case('what do you mean') 

我想要得到WhAt Do YoU MeAn,而不是我得到WhAtDoYoUMeAn。我已經添加了行new_line = new_word +' '。我的問題在哪裏?無法正確處理大寫字符串

回答

2

首先,每次迭代都會覆蓋new_line。其次,new_word正在變得更長,因爲你永遠不會「清除」它。第三,您將空間添加到整個new_line的末尾,而不是每個新單詞後(因爲第二個)。

看評論

def to_weird_case(string): 
    lines = string.split() 
    new_line = '' 
    for word in lines: 
     new_word = '' # start new word from an empty string 
     for item in word: 
      if word.index(item) %2 ==0: 
       item = item.upper() 
       new_word += item 
      else: 
       new_word += item 
     print new_word 
     new_line = new_line + new_word + " " # add new word to the existing new line 
    return new_line 
+0

它工作!我一定很困惑把'new_line'放在哪裏。 –

+0

但是如果我想省略最後的空間呢。它會打印出一些類似於'WhAt Do YoU MeAn'的文字,在句尾有額外的空間。 –

+0

您可以在'返回'之前刪除最後一個空格。雖然不是一個美麗的解決方案:) – Psytho

1

你的代碼沒有重置的new_word的價值和你的循環內覆蓋了new_line,但我想分享一個挨着一家班輪這是正確的與正則表達式的解決方案:

import re 
def to_weird_case(string): 
    return re.sub(r'(\S)(\S?)', lambda m: "{0}{1}".format(m.group(1).upper(), m.group(2)), string); 
print to_weird_case('what do you mean') 

參見Python demo

(\S)(\S?)正則表達式將非空白捕獲到組1中,將一個或零個非空白空間捕獲到組2中,然後在re.sub內將組1的值替換爲大寫的對應值。

看看(\S)(\S?)您如何匹配what do you mean

  • wh是比賽和w是在第1組和h是在第2組(enter image description here)。該匹配作爲m傳遞給lambda表達式,並且組1被修改,並且組2僅按原樣傳遞。
  • 下一場比賽包含at,同樣的事情發生的羣體
  • 接下來,空間也不會因爲\S匹配任何字符,但一個空白匹配。
  • do匹配時,同樣的事情發生,因爲上述
  • 空間描述,yo匹配和處理上述下一個匹配
  • u + 空的空間如所描述的,因爲第二\S具有匹配一個?量詞或者它修改的模式零次出現。因此,第一個字符被大寫,第二個空字符串按原樣使用。
  • 然後其餘的以類似的方式處理。
+1

是的,它更簡單。我走的路很長。 –