2013-10-10 164 views
0
def headAndFoot(s): 
    """precondition: s is a string containing lower-case words and spaces 
    The string s contains no non-alpha characters. 
    postcondition: For each word, capitalize the first and last letter. 
    If a word is one letter, just capitalize it. """ 
    last = len(s) - 1 
    x = s.title() 
    y = x.split() 
    return y 

需要做什麼修改?將字符串中每個單詞的最後一個字母大寫

+0

爲什麼要拆分字符串?你怎麼沒有預覽這個問題,以確保人們可以閱讀它? –

+0

你需要展示一些更多的努力,你能解釋一下你打算怎麼做,爲什麼你認爲它應該工作?然後我們可以幫助你理解你的錯誤並引導你。 – Simon

回答

0

看看我的代碼,並嘗試在你的問題的上下文中使用它。

s = 'The dog crossed the street' 

result = " ".join([x[:-1].title()+x[len(x)-1].upper() for x in s.split()]) 

然後會看到如下

'ThE DoG CrosseD ThE StreeT' 
+0

'x [len(x)-1]'可以變成'x [-1]',jfyi – OmnipotentEntity

-1

進口java.io. *;

公共類ConverT_CapS

{

void main()throws IOException 

{ 

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 

    System.out.println("Enter a sentence "); 

    String str = br.readLine(); 

    str= str.toLowerCase(); 

    StringBuffer sb = new StringBuffer(str); 

    for(int i=1;i<str.length()-1;i++) 
    { 
     if(str.charAt(i+1)==' '||str.charAt(i-1)==' ') 
     { 
      char ch= (char)(str.charAt(i)-32); 
      sb.setCharAt(i,ch); 
     } 
    } 
    sb.setCharAt(0,(char)(str.charAt(0)-32)); 
    sb.setCharAt(str.length()-1,(char)(str.charAt(str.length()-1)-32)); 
    System.out.println(sb); 
} 

}

輸入:什麼烏爾名 輸出:什麼UR名

相關問題