将字符串中每个单词的最后一个字母大写

时间:2013-10-10 03:50:56

标签: python-3.x

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

我需要做出哪些改变?

2 个答案:

答案 0 :(得分: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'

答案 1 :(得分:-1)

import 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);
}

}

输入:你的名字是什么 输出:WhatS UR NamE