I solved this problem here https://www.hackerrank.com/challenges/capitalize
Description: You are given a string . Your task is to capitalize each word of it. In a word only the first character is capitalized. Example 12abc when capitalized remains 12abc - because of this 'title' doesn't work properly with string like '1 w 2 r 3g'. I need to check combinations of digits and lowcase letters. This is my code:
def capitalize(string):
result = list (string.title())
for index in range (len (string)-1):
if string[index].isdigit () and string[index+1].islower ():
result[index+1] = result[index+1].lower()
result = ''.join([char for char in result])
return (result)
But this code is too cumbersome. Can somebody help with a more elegant pythonic decision? Thanks!
The re module can help here:
titlesub = re.compile(r'\b[a-zA-Z]').sub # Precompile regex and prebind method for efficiency
def capitalize(string):
return titlesub(lambda x: x.group(0).upper(), string)
Note: \b handles word/non-word character boundaries (word characters are alphanumeric and underscore), so it will prevent 12abc from capitalizing a, but it won't do so for "abc (which becomes "Abc).
While \b is convenient, it does mean strings like "won't" will be capitalized a "Won'T". If that's an issue, a more targeted selector can be used to capitalize when not preceded by a non-space character:
titlesub = re.compile(r'(?<!\S)[a-zA-Z]').sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With