python - How to capitalize each word after a space leaving the rest of it as is and preserve the space in the end if it exists -


i have following procedure:

def capitalize(self, text):     t = ' '.join([ ''.join([w[0].upper()]+[w[1:]]) w in text.split()])     if text , text[-1] == ' ':         t = ''.join([t] + [' '])     return t 

it takes string text. it's supposed do:

  • capitalize first letter of each string group (word) coming after space , preserve space in end of text if there supplied.

ex:

'home swe eeeet home' -> 'home swe eeeet home' 'hello ooo ooo '      -> 'hello ooo ooo ' (space preserved in end) 

question:

with limited, totally non - expert level of python, tried create procedure memory efficient , fast possible.

  • is approach of converting things list , joining them not keep creating new string efficient in case?

  • is there better, more pythonic way achieve this?

furthermore:

this procedure called each time key pressed onto text field on gui application.

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 string obtained replacing leftmost non-overlapping occurrences of pattern in string replacement repl. if pattern isn’t found, string returned unchanged. repl can string or function.

if repl function, called every non-overlapping occurrence of pattern. function takes single match object argument, , returns replacement string.

\b[a-z] match lowercase character([a-z]) after word boundary (\b).

the lambda function used convert character uppercase; matchobject.match return match group. without argument group 0 assumed. group 0 mean entire match string.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

javascript - addthis share facebook and google+ url -

ios - Show keyboard with UITextField in the input accessory view -