3

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?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61

3 Answers3

1

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.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44
0

You first have to split the line of stdin, then you can operate on each word using a map function. Without splitting, the stdin is only read line by line in the for loop.

#!/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!

General Grievance
  • 4,555
  • 31
  • 31
  • 45
-1

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:

my_string = my_string.capitalize()
my_string = my_string[:-1] + my_string[-1].upper()
Giovanni Rescia
  • 605
  • 5
  • 15