We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Python
- Strings
- Capitalize!
- Discussions
Capitalize!
Capitalize!
Sort by
recency
|
2926 Discussions
|
Please Login in order to post a comment
.title cant working instant can use .split()
While solving this problem, I struggled for a long time on exactly what I did wrong, here I just want to discuss a few tricks I learned while solving!
First off,
.title()method does not work!.title()method makes the first letter of each word uppercase, even if it is not the first character! For example,"123abc"will become"123Abc"And according to the problem, "Note: in a word only the first character is capitalized. Example
"12abc"when capitalized remains"12abc"", thus.title()method does not work!A better alternative would be the
.capitalize()method. It makes the first character of a word uppercase (if it is a letter). For example,"123abc"will stay as"123abc", while"abcde"will become"Abcde"Secondly, be careful of the difference between
.split()and.split(" ").split()method splits a string at whitespaces, but does not preserve the whitespaces! For example,"abc def ghi"(there should be 3 whitespaces between def and ghi, but HackrRank automatically merged it into 1 whitespace) will become["abc", "def", "ghi"]On the other hand,
.split(" ")method also splits a string at whitespaces, but preserves all whitespaces! For example,"abc def ghi"(there should be 3 whitespaces between def and ghi, but HackrRank automatically merged it into 1 whitespace) will become["abc", " ", "def", " ", " ", " ", "ghi"]Lastly, remember that strings are immutable objects!
(P.S. Please let me know if you think I am wrong on any part!)
Easy clean solution def solve(s):