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 Overflow
🌐
Python
peps.python.org › pep-0008
PEP 8 – Style Guide for Python Code | peps.python.org
Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability. Use one leading underscore only for non-public methods and instance variables.
🌐
W3Schools
w3schools.com › python › python_variables_names.asp
Python - Variable Names
Python Examples Python Compiler ... Python Certificate Python Training ... A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume)....
🌐
Data Science for Everyone
matthew-brett.github.io › teaching › string_formatting.html
Inserting values into strings — Tutorials on imaging, computing and mathematics
>>> shepherd = "Mary" >>> string_in_string = "Shepherd {} is on duty.".format(shepherd) >>> print(string_in_string) Shepherd Mary is on duty. The curly braces show where the inserted value should go. You can insert more than one value. The values do not have to be strings, they can be numbers and other Python objects.
🌐
DEV Community
dev.to › spaceofmiah › variable-naming-formats-usecases-49eo
Variable Naming Formats & Usecases - DEV Community
May 24, 2020 - The two names are nice and doesn't go against naming rules, but if we’re to follow python zen which says simple is better than complex then we’ll find that usecase 2 from above names wins. From above code example, variable names are all in uppercase, which is why the variable naming format is ...
Find elsewhere
🌐
The Python Code
thepythoncode.com › article › print-variable-name-and-value-in-python
How to Print Variable Name and Value in Python - The Python Code
They provide a more readable alternative to the older .format() method for string formatting. To create an f-string, you can prepend the string with the letter "f" and then include any Python variable within curly brackets: # Normal way to print variable name and value name = "Abdou" age = 24 print(f"name: {name}, age: {age}")
🌐
Learn Python
learnpython.org › en › String_Formatting
String Formatting - Learn Python - Free Interactive Python Tutorial
The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d". Let's say you ...
🌐
Real Python
realpython.com › python-string-formatting
Python String Formatting: Available Tools and Their Features – Real Python
December 2, 2024 - Python 3.6 added a string interpolation and formatting tool called formatted string literals, or f-strings for short. As you’ve already learned, f-strings let you embed Python objects and expressions inside your strings. To create an f-string, you must prefix the string with an f or F and insert replacement fields in the string literal. Each replacement field must contain a variable, object, or expression:
🌐
Readthedocs
geo-python-site.readthedocs.io › en › 2019.1 › notebooks › L1 › gcp-1-variable-naming.html
Good coding practices - Selecting “good” variable names — Geo-Python site documentation
Again, if we consider the examples from the previous section, we might consider the variable name fmiStationID or simply stationID if we elect to use camelCase. As mentioned in point 1, pothole_case_naming is preferred, mostly because we feel it is the easiest to read and seems to be most common amongst Python programmers.
🌐
Tirkarthi
tirkarthi.github.io › programming › 2019 › 05 › 08 › f-string-debugging.html
f-string debugging in Python 3.8
May 8, 2019 - This caused users to write f"name = {name}" and can get unwieldy when variable names are long like filtered_data_from_third_party would be written as f"filtered_data_from_third_party = {filtered_data_from_third_party}". In those cases we resort to shorter names we understand easily at the context like f"filtered data {filtered_data_from_third_pary}". f-strings also support format specifiers so you can write f"{name!r}" which is same as f"{repr(name)}". Given the above boilerplate an idea was posted in python-ideas around a format specifier where you can use it and the f-string would expand like a macro into <variable_name> = <value_of_variable>. Initially !d was chosen so f"{name!d}" would expand to f"name={repr(name)}".
Top answer
1 of 4
58

You can use the str.format() method, which lets you interpolate other variables for things like the width:

'Number {i}: {num:{field_size}.2f}'.format(i=i, num=num, field_size=field_size)

Each {} is a placeholder, filling in named values from the keyword arguments (you can use numbered positional arguments too). The part after the optional : gives the format (the second argument to the format() function, basically), and you can use more {} placeholders there to fill in parameters.

Using numbered positions would look like this:

'Number {0}: {1:{2}.2f}'.format(i, num, field_size)

but you could also mix the two or pick different names:

'Number {0}: {1:{width}.2f}'.format(i, num, width=field_size)

If you omit the numbers and names, the fields are automatically numbered, so the following is equivalent to the preceding format:

'Number {}: {:{width}.2f}'.format(i, num, width=field_size)

Note that the whole string is a template, so things like the Number string and the colon are part of the template here.

You need to take into account that the field size includes the decimal point, however; you may need to adjust your size to add those 3 extra characters.

Demo:

>>> i = 3
>>> num = 25
>>> field_size = 7
>>> 'Number {i}: {num:{field_size}.2f}'.format(i=i, num=num, field_size=field_size)
'Number 3:   25.00'

Last but not least, of Python 3.6 and up, you can put the variables directly into the string literal by using a formatted string literal:

f'Number {i}: {num:{field_size}.2f}'

The advantage of using a regular string template and str.format() is that you can swap out the template, the advantage of f-strings is that makes for very readable and compact string formatting inline in the string value syntax itself.

2 of 4
8

I prefer this (new 3.6) style:

name = 'Eugene'
f'Hello, {name}!'

or a multi-line string:

f'''
Hello,
{name}!!!
{a_number_to_format:.1f}
'''

which is really handy.

I find the old style formatting sometimes hard to read. Even concatenation could be more readable. See an example:

'{} {} {} {} which one is which??? {} {} {}'.format('1', '2', '3', '4', '5', '6', '7')
Top answer
1 of 2
141

Named replacement fields (the {...} parts in a format string) match against keyword arguments to the .format() method, and not positional arguments.

Keyword arguments are like keys in a dictionary; order doesn't matter, as they are matched against a name.

If you wanted to match against positional arguments, use numbers:

"{0} {1}".format(10, 20)

In Python 2.7 and up, you can omit the numbers; the {} replacement fields are then auto-numbered in order of appearance in the formatting string:

"{} {}".format(10, 20) 

The formatting string can match against both positional and keyword arguments, and can use arguments multiple times:

"{1} {ham} {0} {foo} {1}".format(10, 20, foo='bar', ham='spam')

Quoting from the format string specification:

The field_name itself begins with an arg_name that is either a number or a keyword. If it’s a number, it refers to a positional argument, and if it’s a keyword, it refers to a named keyword argument.

Emphasis mine.

If you are creating a large formatting string, it is often much more readable and maintainable to use named replacement fields, so you don't have to keep counting out the arguments and figure out what argument goes where into the resulting string.

You can also use the **keywords calling syntax to apply an existing dictionary to a format, making it easy to turn a CSV file into formatted output:

import csv

fields = ('category', 'code', 'price', 'description', 'link', 'picture', 'plans')
table_row = '''\
    <tr>
      <td><img src="{picture}"></td>
      <td><a href="{link}">{description}</a> ({price:.2f})</td>
   </tr>
'''

with open(filename, 'rb') as infile:
    reader = csv.DictReader(infile, fieldnames=fields, delimiter='\t')
    for row in reader:
        row['price'] = float(row['price'])  # needed to make `.2f` formatting work
        print table_row.format(**row)

Here, picture, link, description and price are all keys in the row dictionary, and it is much easier to see what happens when I apply the row to the formatting string.

2 of 2
8

Added benefits include

  • You don't have to worry about the order of the arguments. They will fall in the right place in the strings as indicated by their names in the formatter.
  • You can put the same argument in a string twice, without having to repeat the argument. E.g. "{foo} {foo}".format(foo="bar") gives 'bar bar'

Note that you can give extra arguments without causing errors as well. All this is especially useful when

  • you change the string formatter later on with less changes and thus smaller posibility for mistakes. If it does not contain new named arguments, the format function will still work without changing the arguments and put the arguments where you indicate them in the formatter.
  • you can have multiple formatter strings sharing a set of arguments. In this case you could for instance have a dictionary with the all arguments and then pick them out in the formatter as you need them.

E.g.:

>d = {"foo":"bar", "test":"case", "dead":"beef"}
>print("I need foo ({foo}) and dead ({dead})".format(**d))
>print("I need test ({test}) and foo ({foo}) and then test again ({test})".format(**d))
I need foo (bar) and dead (beef)
I need test (case) and foo (bar) and then test again (case)
🌐
Devcamp
bottega.devcamp.com › full-stack-development-javascript-python › guide › python-best-practices-variable-naming-style
Python Best Practices for Variable Naming and Style
Name is self-explanatory because it is only one word. However, whenever you have a variable that has multiple words such as post count, the common convention is to put an underscore in between the words. This is because another developer may look at your code or you could build a package for someone else to use. When doing so, you want to be able to use the standard conventions that other Python developers are using because, if not, it may look as so:
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-string-formatters-in-python-3
How To Use String Formatters in Python 3 | DigitalOcean
August 20, 2021 - Info: To follow along with the example code in this tutorial, open a Python interactive shell on your local system by running the python3 command. Then you can copy, paste, or edit the examples by adding them after the >>> prompt. ... OutputSammy has 5 balloons. In the example above, we constructed a string with a pair of curly braces as a placeholder: ... We then added the str.format() method and passed the value of the integer 5 to that method. This places the value of 5 into the string where the curly braces were: Sammy has 5 balloons. We can also assign a variable to be equal to the value of a string that has formatter placeholders: