Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I pad an fstring with dictionary values in

I can use fstring with a dictionary:

mydict = {'foo': 'py', 'bar': 'thon'}
print(f"I am using {mydict['foo']}{mydict['bar']}")
> I am using python

I can also pad strings:

f"{'Foo': <16} Bar"
>'Foo              Bar'

I want to be able to pad a string that’s coming from my dictionary inside my fstring.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried:

f"{{mydict['foo']}: <16} {mydict['bar']}"

The error here is:

File "", line 1
SyntaxError: f-string: single ‘}’ is not allowed

Is this possible or do I have to add the padded string to my dictionary first before using?

>Solution :

the inner {} is superfluous:

mydict = {'foo': 'py', 'bar': 'thon'}
f"{mydict['foo']: <16} {mydict['bar']}"

works.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading