6

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?

Mazdak
  • 105,000
  • 18
  • 159
  • 188
O.Kokla
  • 63
  • 1
  • 4

4 Answers4

12

You can use title():

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

Example from the console:

>>> 'jordan-bellfort image'.title()
'Jordan-Bellfort Image'
Tiger-222
  • 6,677
  • 3
  • 47
  • 60
  • @Kasramvd nice. – levi Sep 05 '16 at 16:17
  • As the documentation says: `title` uses a simple language-independent definition of a word as groups of consecutive letters. So it count "jordan-bellfort" as two words: "jordan" and "bellfort". Read the doc ;) – Tiger-222 Sep 05 '16 at 16:27
2

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!
--------------------------------------------------------------------------------
BPL
  • 9,632
  • 9
  • 59
  • 117
1

Use string.capwords()instead

Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join()

import string
string.capwords(firstn, "-")
rafaelc
  • 57,686
  • 15
  • 58
  • 82
0

This is a real problem! It is seemingly easily solved with .title() and the like but these suggestions do not solve the actual problem of processing any human name. As in McCormack, O'Brien or de Araugo.

Luckily this is a problem that has been solved. See nameparser

>>> from nameparser import HumanName
>>> name = HumanName('Shirley Maclaine') # Don't change mixed case names
>>> name.capitalize(force=True)
>>> str(name)
'Shirley MacLaine'
Bruno
  • 898
  • 14
  • 17