Home > Mobile >  How to add a string inside an f-string while formatting it in Python?
How to add a string inside an f-string while formatting it in Python?

Time:03-29

I was padding an output in a print statement with a simple code which uses .format() function

print('{:-<100}'.format('xyz'))

I was able to get a similar output using f-strings by creating a new variable

library = 'xyz' 
print(f'{library:-<100}')

Question: Is there a way to add the string 'xyz' inside the f-string without having to create a new variable?

I tried the code below, but it gave me an error:

print(f'xyz:-<100')

CodePudding user response:

If I'm not mistaken, what you want to do is:

print(f"{'xyz':-<100}")  # You can use expressions here, not only variables!

PS: Regarding the error, are you sure you are running Python 3.6?

CodePudding user response:

If I understand your question right, then:

You can just use double-qouted string inside single-quoted f-string

print(f'{"xyz":-<100}')

and optional without f-string and format

print("xyz".ljust(100, "-"))

CodePudding user response:

Yes, there is a way to add the string ('xyz') inside the fstring without having to create a new variable.

Just add the string 'xyz' outside of the curly brackets '{}'

Example: print(f'xyz{:-<100}')

  • Related