是否可以使用字符串格式来大写单词?例如,
"{user} did such and such.".format(user="foobar")
Run Code Online (Sandbox Code Playgroud)
应该回归"Foobar做过这样的事情."
请注意,我很清楚.capitalize(); 但是,这是我正在使用的代码(非常简化版本):
printme = random.choice(["On {date}, {user} did la-dee-dah. ",
"{user} did la-dee-dah on {date}. "
])
output = printme.format(user=x,date=y)
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,只是定义user为x.capitalize()在.format()不工作的,因为那么它也将适用(错误地)的第一个场景.由于我无法预测命运,因此无法知道哪些random.choice会提前被选中.我能做什么?
Addt'l note:正好output = random.choice(['xyz'.format(),'lmn'.format()])(换句话说,单独格式化每个字符串,然后.capitalize()用于需要它的那些字符串)不是一个可行的选项,因为printme实际上是从~40 +字符串中选择.
我发现在Python 3中使用.format()方法进行字符串格式化的可能性,但是我提出了一个我不理解的错误。
因此,为什么以下行可以[让我认为可以完全像传递给format()的参数那样使用“ 0”]:
s = 'First letter of {0} is {0[0]}'.format("hello")
#gives as expected: 'First letter of hello is h'
Run Code Online (Sandbox Code Playgroud)
但这不是[在{0}中将方法或函数应用于0无效吗?]:
s = '{0} becomes {0.upper()} with .upper() method'.format("hello")
Run Code Online (Sandbox Code Playgroud)
引发以下错误:
AttributeError: 'str' object has no attribute 'upper()'
Run Code Online (Sandbox Code Playgroud)
为什么引发的错误说明我已将upper用作属性而不是方法?还有另一种方法可以做到:
s = '{} becomes {} with .upper() method'.format("hello","hello".upper())
#gives as expected: 'hello becomes HELLO with .upper() method'
Run Code Online (Sandbox Code Playgroud)
谢谢!