How to pass string format as a variable to an f-string
f-string, python, string
Solution
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
Problem
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.