26

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.

lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228

2 Answers2

41

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

Brown Bear
  • 19,655
  • 10
  • 58
  • 76
3

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...

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561