yuuske
yuuske

Reputation: 43

Python String Capitalize

from string import capwords

t = "\"i'm happy,\" said tanby"
sText = t.split()
rText = []

for str in sText:
    if '\"' in str[0]:
        t = capwords(str, sep='\"')
        rText.append(t)
    else:
        t = capwords(str)
        rText.append(t)

print(' '.join(rText))

>>> "I'm Happy," Said Tanby
     ^   ^       ^    ^

Ignore quotes and capitalize. When used title(), become " I'M and when used capwords(), become " i'm. Is there a better way?

Upvotes: 0

Views: 514

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177396

The quotes interfere with the capwords algorithm. Using re.sub with a pattern allowing single quotes in words fixes it. The regular expression matches one or more \w (word characters) or single quotes. Each match is passed to the lambda function and capitalized for the replacement.

>>> import re
>>> s='"i\'m happy," said tanby'
>>> print(re.sub(r"\b[\w']+\b",lambda m: m.group().capitalize(),s))
"I'm Happy," Said Tanby

Upvotes: 3

Related Questions