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?
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.
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.
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.
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.
You can use title():
print('Good day,', firstn.title(), lastn.title(), '!')
Example from the console:
>>> 'jordan-bellfort image'.title()
'Jordan-Bellfort Image'
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!
--------------------------------------------------------------------------------
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With