Reputation: 14671
I have the following procedure:
def capitalize(self, text):
t = ' '.join([ ''.join([w[0].upper()]+[w[1:]]) for w in text.split()])
if text and text[-1] == ' ':
t = ''.join([t] + [' '])
return t
It takes a string text. What it's supposed to do:
ex:
'home swe eeeet home' -> 'Home Swe Eeeet Home'
'heLLo OoO ooo ' -> 'HeLLo OoO Ooo ' (space preserved in the end)
Question:
With my limited, totally non - expert level of Python, I tried to create this procedure as memory efficient and as fast as possible.
Is the approach of converting things into list and joining them to not to keep creating a new string efficient in this case?
Is there a better, more pythonic way to achieve this?
Furthermore:
This procedure is called each time a key is pressed onto a text field on a GUI application.
Upvotes: 2
Views: 3206
Reputation: 1
def title(s):
return(' '.join(x.capitalize() for x in s.split(' ')))
# Or alternatively:
#y = []
#for x in s.split(' '):
# y.append(x.capitalize())
#return ' '.join(y)
Upvotes: 0
Reputation: 369274
Use re.sub:
>>> import re
>>> re.sub(r'\b[a-z]', lambda m: m.group().upper(), 'home swe eeeet home')
'Home Swe Eeeet Home'
>>> re.sub(r'\b[a-z]', lambda m: m.group().upper(), 'heLLo OoO ooo ')
'HeLLo OoO Ooo '
re.sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function.
If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.
\b[a-z]
match any lowercase character([a-z]
) after the word boundary (\b
).
The lambda function was used to convert the character to uppercase; MatchObject.match return match group. Without argument group 0 is assumed. Group 0 mean entire match string.
Upvotes: 2