lmiguelvargasf
lmiguelvargasf

Reputation: 69745

How to pass string format as a variable to an f-string

I am using f-strings, and I need to define a format that depends upon a variable.

def display_pattern(n):
    temp = ''
    for i in range(1, n + 1):
        temp = f'{i:>3}' + temp
        print(temp)

If it is relevant, the output of display_pattern(5) is:

  1
  2  1
  3  2  1
  4  3  2  1
  5  4  3  2  1

I wonder if it is possible to manipulate the format >3, and pass a variable instead. For example, I have tried the following:

def display_pattern(n):
    spacing = 4
    format_string = f'>{spacing}' # this is '>4'
    temp = ''
    for i in range(1, n + 1):
        temp = f'{i:format_string}' + temp
        print(temp)

However, I am getting the following error:

Traceback (most recent call last):
  File "pyramid.py", line 15, in <module>
    display_pattern(8)
  File "pyramid.py", line 9, in display_pattern
    temp = f'{i:format_string}' + temp
ValueError: Invalid format specifier

Is there any way I can make this code work? The main point is being able to control the spacing using a variable to determine the amount of padding.

Upvotes: 31

Views: 23685

Answers (2)

user8060120
user8060120

Reputation:

you should to put the format_string as variable

temp = f'{i:{format_string}}' + temp

the next code after : is not parsed as variable until you clearly indicate. And thank @timpietzcker for the link to the docs: formatted-string-literals

Upvotes: 52

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

You need to keep the alignment and padding tokens separate from each other:

def display_pattern(n):
    padding = 4
    align = ">"
    temp = ''
    for i in range(1, n + 1):
        temp = f'{i:{align}{padding}}' + temp
        print(temp)

EDIT:

I think this isn't quite correct. I've done some testing and the following works as well:

def display_pattern(n):
    align = ">4"
    temp = ''
    for i in range(1, n + 1):
        temp = f'{i:{align}}' + temp
        print(temp)

So I can't really say why your method wouldn't work...

Upvotes: 2

Related Questions