大写连字符名称(capitalize hyphenated words)

我有一个脚本看起来像这样:

我有一个脚本看起来像这样:

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

它将很好地使用简单的名字,如杰克 · 布莱克或摩根 · 梅曼,但是当我输入像jordan-bellfort image这样的连字符名称时,我期望"Jordan-Bellfort Image",但我收到"Jordan-bellfort Image"

我怎样才能让 python 在连字符之后大写字符?

12

您可以使用title()

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

来自控制台的示例:

>>> 'jordan-bellfort image'.title()
'Jordan-Bellfort Image'
2

我建议只使用str.title,这里是一个工作示例,比较您的版本和使用 str.title 方法的版本:

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)

导致这一点:

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!
--------------------------------------------------------------------------------
1

改用string.capwords()

使用 str.split()将参数拆分为单词,使用 str.capitalize()将每个单词大写,并使用 str.join()连接大写的单词

import string
string.capwords(firstn, "-")
0

这是一个真正的问题!用.title()等似乎很容易解决,但这些建议并不能解决处理任何人名的实际问题。如McCormackO'Briende Araugo

幸运的是,这个问题已经解决了。请参阅namepr

>>> from namepr import HumanName
>>> name = HumanName('Shirley Maclaine') # Don't change mixed case names
>>> name.capitalize(force=True)
>>> str(name)
'Shirley MacLaine'

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(679)
FFMPEG-将DTS音频转换为 AC3-但保留原始视频和音频文件
上一篇
定义原子函数(atom function)
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(25条)