Python – Problems title-casing a string in Python

pythonstringuppercase

I have a name as a string, in this example "markus johansson".

I'm trying to code a program that makes 'm' and 'j' uppercase:

name = "markus johansson"

for i in range(1, len(name)):
    if name[0] == 'm':
        name[0] = "M"
    if name[i] == " ":
        count = name[i] + 1
    if count == 'j':    
            name[count] = 'J'  

I'm pretty sure this should work, but it gives me this error:

File "main.py", line 5 in <module> 
   name[0] = "M" 
TypeError: 'str' object does support item assignment 

I know there is a library function called .title(), but I want to do "real programming".

How do I fix this?

Best Solution

I guess that what you're trying to achieve is:

from string import capwords
capwords(name)

Which yields:

'Markus Johansson'

EDIT: OK, I see you want to tear down a open door. Here's low level implementation.

''.join([char.upper() if prev==' ' else char for char,prev in zip(name,' '+name)])