Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Write a function that capitalizes the first and fourth letters of a name
The output should be
-->
old_macdonald('macdonald') --> MacDonald

Python
def old_macdonald(name):
    a=name.capitalize()
    b=a[3].capitalize()
    c=a.replace(a[3],b,1)
    return c

The above code works fine.But the below one isnt working and i m not able to get why isnt it working
Python
def old_macdonald(name):
    a=name.replace(name[3],name[3].capitalize(),1)
    b=a.capitalize()
    return b


What I have tried:

I tried in second way,i didnt get why that code doesnt work
Posted
Updated 15-Apr-21 21:37pm
v2

According to the documentation[^] str.capitalize() does the following:
Return a copy of the string with its first character capitalized and the rest lowercased.

Your code line b=a.capitalize() undoes the changes done on the previous line.
 
Share this answer
 
Comments
CPallini 16-Apr-21 3:38am    
5.
Because the second call to capitalize removes the effect of the first one

Python
def old_macdonald(name):
    a=name.replace(name[3],name[3].capitalize(),1) # this makes the fourth character uppercase
    b=a.capitalize() # this makes the first character uppercase AND the fourh character Lowercase
    return b

See, for instance: string capitalize() in Python - GeeksforGeeks[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900