简体   繁体   English

如何在 Python 格式说明符中使用变量名

[英]How can you use a variable name inside a Python format specifier

Is it possible to use a variable inside of a Python string formatting specifier?是否可以在 Python 字符串格式说明符中使用变量?

I have tried:我试过了:

display_width = 50
print('\n{:^display_width}'.format('some text here'))

but get a ValueError: Invalid format specifier .但得到一个ValueError: Invalid format specifier I have also tried display_width = str(50)我也试过display_width = str(50)

however, just entering print('\\n{:^50}'.format('some text here')) works just fine.但是,只需输入print('\\n{:^50}'.format('some text here'))就可以了。

Yes, but you have to pass them in as arguments to format , and then refer to them wrapped in {} like you would the argument name itself:是的,但您必须将它们作为参数传递给format ,然后像使用参数名称本身一样引用它们包裹在{}

print('\n{:^{display_width}}'.format('some text here', display_width=display_width))

Or shorter but a little less explicit:或者更短但不那么明确:

print('\n{:^{}}'.format('some text here', display_width))

Since this question was originally posted, Python 3.6 has added f-strings, which allow you to do this without using the format method and it uses variables which are in scope rather than having to pass in the named variables as keyword arguments:由于这个问题最初是发布的,Python 3.6 添加了 f-strings,它允许您在不使用format方法的情况下执行此操作,并且它使用范围内的变量,而不必将命名变量作为关键字参数传入:

display_width = 50
text = 'some text here'
print(f'\n{text:^{display_width}}')

Python f-string is more flexible. Python f-string 更灵活。

>>> display_width = 50
>>> display_content = "some text here"
>>> print(f'\n{display_content:^{display_width}}')

                  some text here

It seems like since this question was first posted, python introduced f-strings.似乎自从这个问题首次发布以来,python 引入了 f-strings。 See this web page for info.有关信息,请参阅此网页

>>> name = 'Fred'
>>> age = 42
>>> f'He said his name is {name} and he is {age} years old.'
He said his name is Fred and he is 42 years old.

也许

print(('{0:^'+str(display_width)+'}').format('hello'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM