Arkistarvh Kltzuonstev
Arkistarvh Kltzuonstev

Reputation: 6920

Python : Capitalize first character of words in a string except one word

I have string a = 'thirteen thousand and forty six'. The variable a would always hold some amount in words. I want to capitalize first characters of each word in the string, except the specific word 'and'. Here is my code which is working fully :

b = []
for i in a.split():
    if i.lower() == 'and':
        b.append(i.lower())
    else:
        b.append(i.capitalize())
aa = " ".join(b)    #'Thirteen Thousand and Forty Six'

Another piece of oneliner I tried is :

aa = " ".join([k.capitalize() for k in a.split() if k.lower() != 'and'])

but, it returns 'Thirteen Thousand Forty Six' as the resultant string, omitting the word 'and'.

Question is whether there are any possible oneliners using list comprehension or some inbuilt functions (without using regex) for this work?

Upvotes: 0

Views: 1243

Answers (4)

Shivam
Shivam

Reputation: 51

The following snippet might be useful, It simply gives the desired output in single line python code:

s = 'thirteen thousand and forty six'
print(s.title().replace('And', 'and'))

Upvotes: 1

Manfre Lörson
Manfre Lörson

Reputation: 7

you could just replace "And with and" after capitalizing

a = 'thirteen thousand and forty six'
(' ').join([x.capitalize() for x in a.split(' ')]).replace('And', 'and')

Upvotes: -1

Selcuk
Selcuk

Reputation: 59184

The correct syntax should be

aa = " ".join([k.capitalize() if k.lower() != 'and' else k for k in a.split()])

When you put your if clause at the end of comprehension it will skip elements that don't satisfy the condition. Your requirement, however, is to return the item verbatim when it is "and".

Upvotes: 4

aghast
aghast

Reputation: 15310

Instead of splitting on the default (split()) why not split on the " and ", and re-join using "and" as well?

aa = " and ".join([word.capitalize() for word in a.split(" and ")])

Upvotes: 1

Related Questions