1

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')
2
  • 2
    print(f"{'xyz':-<100}") Commented Mar 28, 2022 at 13:55
  • If you have just a single literal string, I would just use print('xyz'.ljust(100, '-')). (It's actually faster than the corresponding f-string.) (Not that I'd care much either way, but it nips the "f-strings are faster" argument against it.) Commented Mar 28, 2022 at 14:09

3 Answers 3

2

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, "-"))
Sign up to request clarification or add additional context in comments.

Comments

1

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?

4 Comments

The error is presumably a NameError for the undefined name xyz; the OP is already successfully using an f-string with a variable.
@chepner there are no {} surrounding the expression within the f-string, though, so there is no reason his code should throw an error. I ran it myself in both Python 3 and Python 2, and it only gave an error in 2.
I'm assuming a typo in the question, rather than a problem in the actual code.
thanks @Xiddoc the double quotes inside the single quotes / single quotes inside the double quotes does the trick for me. FYI : 'xyz' is a random string literal and not a variable. Apologies if the quesiton had a typo.
0

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}')

1 Comment

This gives error, SyntaxError: f-string: valid expression required before ':'. Are you sure this works?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.