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.
When using f-Strings to display variables, you only need to specify the names of the variables inside a set of curly braces {} . And at runtime, all variable names will be replaced with their respective values.
Essentially, you have three options; The first is to define a new line as a string variable and reference that variable in f-string curly braces. The second workaround is to use os. linesep that returns the new line character and the final approach is to use chr(10) that corresponds to the Unicode new line character.
The formatting using % is similar to that of 'printf' in C programming language. %d – integer %f – float %s – string %x – hexadecimal %o – octal The below example describes the use of formatting using % in Python.
Instead of using the locals() and the globals() function to convert a string to a variable name in python, we can also use the vars() function. The vars() function, when executed in the global scope, behaves just like the globals() function.
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
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With