1

I just started to learn python a few months ago so I'm a newbie here. I was trying to capitalize the first letter of every word in a string. When the input is "hello world" (for example) it works perfectly, but with some inputs like "i love coding" it returns this "I Love CodIng" and it just doesn't make sense to me. Could someone explain to me why this is happening? Here's the code:

def LetterCapitalize(str):
    str = str.replace(str[0], str[0].upper())
    for i in range(len(str)):
        try:
            if str[i] == ' ':
                str = str.replace(str[i+1], str[i+1].upper())
            else:
                continue
        except IndexError:
            break
    return str
jkhadka
  • 2,443
  • 8
  • 34
  • 56
Sebastian
  • 23
  • 2

2 Answers2

1

The str.replace method replaces all occurrences of the given substring in the given main string, so by replacing the letter i with I in i love coding it replaces both is in the string.

Since strings are immutable you can instead convert the given string to a list of characters, so that you can iterate through the list, replace the character if it's either at the start of the string or preceded by a space, and join the list back to a string in the end:

def LetterCapitalize(s):
    l = list(s)
    for i, c in enumerate(l):
        if not i or l[i - 1] == ' ':
            l[i] = c.upper()
    return ''.join(l)

so that LetterCapitalize('i love coding') returns:

I Love Coding
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Thank you so much. I just don't understand what is the use of "if not i". – Sebastian Feb 26 '19 at 02:11
  • Glad to be of help. `if not i` is equivalent to `if i == 0` here, since `0` is a false value. It's there to account for the start of the string, where there can't be a preceding space. – blhsing Feb 26 '19 at 09:36
0

The problem with the code is your first line, str = str.replace(str[0], str[0].upper())
Here you replace first letter with its capital, but also you replace that letter in all the following string.

Example : LetterCapitalize("hello hoher") -> 'Hello HoHer'

You need to modify single character at a given position in the string and not replace all the occurring letters. You should try to work with string as a list. Here is a helpful link : Change one character in a string?

jkhadka
  • 2,443
  • 8
  • 34
  • 56