Python:使用 string.format() 将单词大写 [英] Python: Capitalize a word using string.format()

查看:32
本文介绍了Python:使用 string.format() 将单词大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用字符串格式将单词大写?例如,

Is it possible to capitalize a word using string formatting? For example,

"{user} did such and such.".format(user="foobar")

应该返回Foobar做了什么."

should return "Foobar did such and such."

请注意,我很清楚.capitalize();但是,这是我正在使用的(非常简化的版本)代码:

Note that I'm well aware of .capitalize(); however, here's a (very simplified version of) code I'm using:

printme = random.choice(["On {date}, {user} did la-dee-dah. ",
                         "{user} did la-dee-dah on {date}. "
                         ])

output = printme.format(user=x,date=y)

如您所见,仅在 .format() 中将 user 定义为 x.capitalize() 是行不通的,因为那么它也将(错误地)应用于第一个场景.而且由于我无法预测命运,因此无法提前知道会选择哪个 random.choice.我能做什么?

As you can see, just defining user as x.capitalize() in the .format() doesn't work, since then it would also be applied (incorrectly) to the first scenario. And since I can't predict fate, there's no way of knowing which random.choice would be selected in advance. What can I do?

补充说明: 只是做 output = random.choice(['xyz'.format(),'lmn'.format()])(在换句话说,单独格式化每个字符串,然后对需要它的人使用 .capitalize() 不是一个可行的选择,因为 printme 实际上是从 ~40 多个字符串.

Addt'l note: Just doing output = random.choice(['xyz'.format(),'lmn'.format()]) (in other words, formatting each string individually, and then using .capitalize() for the ones that need it) isn't a viable option, since printme is actually choosing from ~40+ strings.

推荐答案

您可以创建自己的 string.Formatter 这将允许您识别自定义 转换,您可以使用它来重新调整字符串.

You can create your own subclass of string.Formatter which will allow you to recognize a custom conversion that you can use to recase your strings.

myformatter.format('{user!u} did la-dee-dah on {date}, and {pronoun!l} liked it. ',
                      user=x, date=y, pronoun=z)

这篇关于Python:使用 string.format() 将单词大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆