32

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.

0

2 Answers 2

55

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

Sign up to request clarification or add additional context in comments.

3 Comments

You can nest variables up to one level: docs.python.org/3/whatsnew/…
yes but the next code after : is not parsed as variable until you clearly indicate.
@bearbrown, thanks for providing a detailed explanation. This solves all my doubts.
2

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

2 Comments

why putting a nested {} works in this case? I mean {align} and {padding} are inside {}.
i think you should not to delete your post it helped me to find the solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.