简体   繁体   English

如何将字符串的第一个和最后一个字母大写?

[英]How to capitalize the first and last letter of a string?

So it's not a very difficult problem and I've been trying to do it.所以这不是一个非常困难的问题,我一直在努力。 Here is my sample code:这是我的示例代码:

import sys

for s in sys.stdin:
    s = s[0:1].upper() + s[1:len(s)-1] + s[len(s)-1:len(s)].upper()
    print(s)

This code only capitalizes the first letter and not the last letter as well.此代码仅将第一个字母大写,最后一个字母也不大写。 Any tips?有小费吗?

You are operating on lines, not words, since iterating over sys.stdin will give you strings that consist of each line of text that you input.您正在对行而不是单词进行操作,因为遍历sys.stdin将为您提供由您输入的每一行文本组成的字符串。 So your logic won't be capitalizing individual words.因此,您的逻辑不会将单个单词大写。

There is nothing wrong with your logic for capitalizing the last character of a string.您将字符串的最后一个字符大写的逻辑没有任何问题。 The reason that you are not seeming to capitalize the end of the line is that there's an EOL character at the end of the line.您似乎没有将行尾大写的原因是行尾有一个 EOL 字符。 The capitalization of EOL is EOL, so nothing is changed. EOL 的大写是 EOL,因此没有任何变化。

If you call strip() on the input line before you process it, you'll see the last character capitalized:如果您在处理之前在输入行上调用strip() ,您将看到最后一个字符大写:

import sys
for s in sys.stdin:
    s = s.strip()
    s = s[0:1].upper() + s[1:len(s)-1] + s[len(s)-1:len(s)].upper()
    print(s)

@Calculuswhiz's answer shows you how to deal with capitalizing each word in your input. @Calculuswhiz 的回答向您展示了如何处理输入中每个单词的大写。

You first have to split the line of stdin, then you can operate on each word using a map function.您首先必须拆分标准输入行,然后您可以使用map function 对每个单词进行操作。 Without splitting, the stdin is only read line by line in the for loop.如果不拆分,stdin 只能在for循环中逐行读取。

#!/usr/bin/python
import sys

def capitalize(t):
    # Don't want to double print single character
    if len(t) is 1:
      return t.upper()
    else:
      return t[0].upper() + t[1:-1] + t[-1].upper()

for s in sys.stdin:
    splitLine = s.split()
    l = map(capitalize, splitLine)
    print(' '.join(l))

Try it online! 在线尝试!

You could just use the capitalize method for str which will do exactly what you need, and then uppercase the last letter individually, something like:您可以只使用strcapitalize方法,这将完全满足您的需要,然后将最后一个字母单独大写,例如:

my_string = my_string.capitalize()
my_string = my_string[:-1] + my_string[-1].upper()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM