-2

How can we achieve the following in Python 3.6 using f-string (instead of using format()) method?

quantity = 3
itemno = 567
price = 49
myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."
print(myorder.format(quantity, itemno, price))

Output:

I want 3 pieces of item number 567 for 49.00 dollars.
4
  • 2
    ...why? What benefit would you hope to gain? Commented May 18, 2024 at 5:24
  • 3
    Index number of what? Commented May 18, 2024 at 5:27
  • 1
    what do you mean? The f-string syntax uses direct refererences to the variables. If you wanted to have some indirection (IF it might improve readabilltiy), you could use another intermediate variable which can be changed but that sounds like it would make code worse
    – moo
    Commented May 18, 2024 at 5:27
  • 2
    Did you try print(f"I want {quantity} pieces of item number {itemno} for {price:.2f} dollars.")? or myorder = f"I want {quantity} pieces of item number {itemno} for {price:.2f} dollars." --- because both worked when I ran them in ipython. So I'm not sure what you're asking. Commented May 18, 2024 at 5:27

2 Answers 2

1
quantity = 3
itemno = 567
price = 49
myorder = f"I want {quantity} pieces of item number {itemno} for {price:.2f} dollars."
print(myorder)

Output:

I want 3 pieces of item number 567 for 49.00 dollars.

Explanation

The f before the string indicates an f-string. {quantity}, {itemno}, and {price:.2f}: These are placeholders where the values of quantity, itemno, and price (formatted to 2 decimal places) are inserted directly into the string.

0

F-string was added in Python 3.6 [python.org] so yes you can use F-string in Python 3.6 and above:

quantity = 3
itemno = 567
price = 49
myorder = F"I want {quantity} pieces of item number {itemno} for {price:.2f} dollars." #[1][2]
print(myorder)

[1] Format specifiers still remain the same.

[2] New in Python 3.12, you can now reuse the same quoting type of the outer F-string inside a replacement field when accessing dict() values using dict() keys.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.