Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 303
Lostsoulaside Avatar asked Dec 10 '25 18:12

Lostsoulaside


1 Answers

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. 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. The capitalization of EOL is EOL, so nothing is changed.

If you call strip() on the input line before you process it, you'll see the last character capitalized:

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.

like image 148
CryptoFool Avatar answered Dec 12 '25 12:12

CryptoFool



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!