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:
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:
display_width = 50
text = 'some text here'
print(f'\n{text:^{display_width}}')
Answer from Brian Campbell on Stack OverflowYes, 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:
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:
display_width = 50
text = 'some text here'
print(f'\n{text:^{display_width}}')
Python f-string is more flexible.
>>> display_width = 50
>>> display_content = "some text here"
>>> print(f'\n{display_content:^{display_width}}')
some text here
Videos
How does the str.format() method work in Python?
What are f-strings, and how do they simplify string formatting in Python?
How can I format strings with both positional and keyword arguments using str.format()?
You could either implement the __format__ method in your object class or place the str() directly in the format string:
print(f"{str(obj):.5}")
see PEP 498 for details.
note that f"{obj!s:.5}" also works but, in that same specification, !s and !r are considered redundant and only maintained for backward compatibility
It works if you explicitly request string conversion:
>>> print(f"{obj!s:.5}")
<obje
Behind the scenes, I suspect that the result of the expression is not passed to str first, but rather to format:
>>> format(obj, "%s")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported format string passed to object.__format__
In this case, object.__format__ itself doesn't automatically do a conversion to string using object.__str__, for whatever reason.