Shane Smiskol
Shane Smiskol

Reputation: 966

Lowercase letter after certain character?

I like some ways of how string.capwords() behaves, and some ways of how .title() behaves, but not one single one.

I need abbreviations capitalized, which .title() does, but not string.capwords(), and string.capwords() does not capitalize letters after single quotes, so I need a combination of the two. I want to use .title(), and then I need to lowercase the single letter after an apostrophe only if there are no spaces between.

For example, here's a user's input:

string="it's e.t.!"

And I want to convert it to:

>>> "It's E.T.!"

.title() would capitalize the 's', and string.capwords() would not capitalize the "e.t.".

Upvotes: 2

Views: 2038

Answers (3)

hemraj
hemraj

Reputation: 1034

if you don't want to use regex , you can always use this simple for loop

s = "it's e.t.!"
capital_s = ''
pos_quote = s.index("'")
for pos, alpha in enumerate(s):
    if pos not in [pos_quote-1, pos_quote+1]:
        alpha = alpha.upper()
    capital_s += alpha
print capital_s

hope this helps :)

Upvotes: 0

hostingutilities.com
hostingutilities.com

Reputation: 9509

a = ".".join( [word.capitalize() for word in "it's e.t.!".split(".")] )
b = " ".join( [word.capitalize() for word in a.split(" ")] )
print(b)

Edited to use the capitalize function instead. Now it's starting to look like something usable :). But this solution doesn't work with other whitespace characters. For that I would go with falsetru's solution.

Upvotes: 1

falsetru
falsetru

Reputation: 369064

You can use regular expression substitution (See re.sub):

>>> s = "it's e.t.!"
>>> import re
>>> re.sub(r"\b(?<!')[a-z]", lambda m: m.group().upper(), s)
"It's E.T.!"

[a-z] will match lowercase alphabet letter. But not after ' ((?<!') - negative look-behind assertion). And the letter should appear after the word boundary; so t will not be matched.

The second argument to re.sub, lambda will return substitution string. (upper version of the letter) and it will be used for replacement.

Upvotes: 8

Related Questions