2

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:

  • Capitalize first letter of each string group (word) coming after a space and preserve the space in the end of the text if there was any supplied.

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.

Phil
  • 13,875
  • 21
  • 81
  • 126

2 Answers2

2

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.

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • Hello. Thank you very much for actually reading the question. ;-) Seems like a rarity. This thing works like magic and does what it's supposed to. Do you think you could explain how it works though please? It would make it much better. Thank you, once again. – Phil Aug 15 '13 at 19:17
  • 1
    @Phil, I added an explanation. – falsetru Aug 16 '13 at 01:18
0
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)
  • Hello. This wouldn't work. Please read the question and see the provided examples. – Phil Aug 31 '13 at 14:08
  • Please add a small explanatory text which explains what syntax you used and how this is evaluated. It will help understanding what this one-liner does. – Sumurai8 Aug 31 '13 at 14:10