如何在 Python 格式说明符中使用变量名
How can you use a variable name inside a Python format specifier
是否可以在 Python 字符串格式说明符中使用变量?
我试过:
display_width = 50
print('\n{:^display_width}'.format('some text here'))
但得到 ValueError: Invalid format specifier
。我也试过display_width = str(50)
然而,只要输入 print('\n{:^50}'.format('some text here'))
就可以了。
是的,但是您必须将它们作为参数传递给 format
,然后像引用参数名称本身一样引用包含在 {}
中的它们:
print('\n{:^{display_width}}'.format('some text here', display_width=display_width))
或更短但不那么明确:
print('\n{:^{}}'.format('some text here', display_width))
由于最初发布了这个问题,Python 3.6 添加了 f 字符串,它允许您在不使用 format
方法的情况下执行此操作,并且它使用范围内的变量而不是具有将命名变量作为关键字参数传递:
display_width = 50
text = 'some text here'
print(f'\n{text:^{display_width}}')
可能
print(('{0:^'+str(display_width)+'}').format('hello'))
似乎自从首次发布此问题后,python 就引入了 f 弦。有关信息,请参阅 this web page。
>>> 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.
Python f-string 更灵活。
>>> display_width = 50
>>> display_content = "some text here"
>>> print(f'\n{display_content:^{display_width}}')
some text here
是否可以在 Python 字符串格式说明符中使用变量?
我试过:
display_width = 50
print('\n{:^display_width}'.format('some text here'))
但得到 ValueError: Invalid format specifier
。我也试过display_width = str(50)
然而,只要输入 print('\n{:^50}'.format('some text here'))
就可以了。
是的,但是您必须将它们作为参数传递给 format
,然后像引用参数名称本身一样引用包含在 {}
中的它们:
print('\n{:^{display_width}}'.format('some text here', display_width=display_width))
或更短但不那么明确:
print('\n{:^{}}'.format('some text here', display_width))
由于最初发布了这个问题,Python 3.6 添加了 f 字符串,它允许您在不使用 format
方法的情况下执行此操作,并且它使用范围内的变量而不是具有将命名变量作为关键字参数传递:
display_width = 50
text = 'some text here'
print(f'\n{text:^{display_width}}')
可能
print(('{0:^'+str(display_width)+'}').format('hello'))
似乎自从首次发布此问题后,python 就引入了 f 弦。有关信息,请参阅 this web page。
>>> 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.
Python f-string 更灵活。
>>> display_width = 50
>>> display_content = "some text here"
>>> print(f'\n{display_content:^{display_width}}')
some text here