Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalizing hyphenated name

I have a script looking like this:

firstn = input('Please enter your first name: ') 
lastn = input('Please enter Your last name: ') 
print('Good day, ' + str.capitalize(firstn) + ' ' + str.capitalize(lastn)+ '!')

It will work nicely with simple names like jack black or morgan meeman but when I input hyphenated name like jordan-bellfort image then I'd expect "Jordan-Bellfort Image" but I receive "Jordan-bellfort Image".

How can I get python to capitalize the character right after hyphen?

like image 759
O.Kokla Avatar asked Sep 05 '16 16:09

O.Kokla


People also ask

Do you capitalize hyphenated words in a title?

Capitalization of hyphenated words in general is really more a question of style than anything else. When capitalizing hyphenated words in a title, choose a style and follow it consistently. All-American flag-waving techniques. A New Park-and-Ride Lot for Commuters.

Do you capitalize the first element in a hyphenated compound?

The Chicago Manual of Style has simplified its capitalization rules in its most recent (17th) edition. For hyphenated compounds, it recommends: Always capitalize the first element.

Do you capitalize the last word in a title?

Beyond that, all three capitalize the first and last word of a title. Considering those rules, these hyphenated words would all be correctly capitalized in titles: In the list above, up, in, on, off, and out are adverbs–not prepositions.

Is the word up capitalized in a title?

In tune-up, up is an adverb (not a preposition such as in "up the street"). Adverbs are capitalized in titles–even when they are the last part of a hyphenated compound.


2 Answers

You can use title():

print('Good day,', firstn.title(), lastn.title(), '!')

Example from the console:

>>> 'jordan-bellfort image'.title()
'Jordan-Bellfort Image'
like image 147
Tiger-222 Avatar answered Sep 23 '22 14:09

Tiger-222


I'd suggest just using str.title, here's a working example comparing your version and the one using str.title method:

import string

tests = [
    ["jack", "black"],
    ["morgan", "meeman"],
    ["jordan-bellfort", "image"]
]

for t in tests:
    firstn, lastn = t
    print('Good day, ' + str.capitalize(firstn) +
          ' ' + str.capitalize(lastn) + '!')
    print('Good day, ' + firstn.title() + ' ' + lastn.title() + '!')
    print('-'*80)

Resulting into this:

Good day, Jack Black!
Good day, Jack Black!
--------------------------------------------------------------------------------
Good day, Morgan Meeman!
Good day, Morgan Meeman!
--------------------------------------------------------------------------------
Good day, Jordan-bellfort Image!
Good day, Jordan-Bellfort Image!
--------------------------------------------------------------------------------
like image 33
BPL Avatar answered Sep 26 '22 14:09

BPL