python string formatting example with the explanation

python string formatting

Preview what we going to learn:


Write a program in Python using the following scenario:

Your customer is a restaurant owner that wants to be able to advertise online in chat rooms, but they have an ever-changing menu. Write a program in Python that will prompt the user for the name of a restaurant, three menu items, and their prices. See example input and output below.

This is the solution to the assignment which you can download here.

Example:

Input:

Famous Bill's Eatery
BLT Sandwich
11.99
Fries
1.49
Drink
1.19

Output:

output of python string

Python code:

# max len 25
restaurant = input()
# item 1
# max len 12
item1 = input()
# max 99.99
item1_price = float(input())
# item 2
item2 = input()
item2_price = float(input())
# item 3
item3 = input()
item3_price = float(input())
# size of display 33 
br = '*'*33

print()
print(br)

a = "{}{:^25}{}".format('*'*4, restaurant, '*'*4)
print(a)

print(br)

b = "* "+"{:<23}".format(item1)+"{:>6}".format('$'+str(item1_price))+" *"
print(b)

c = "* "+"{:<23}".format(item2)+"{:>6}".format('$'+str(item2_price))+" *"
print(c)

d = "* "+"{:<23}".format(item3)+"{:>6}".format('$'+str(item3_price))+" *"
print(d)

print(br)

Terminal output and input:



Explanation:

There are many ways to solve this problem but we can use string formatting in python to do this task accurately.

Example:

s = "{} and {} and {}".format(1,2,3)

var = "string"
s = "this is a {}".format(var)

These are normal examples of string formatting.

printing output:

1)

br = '*'*33
print(br)

This print ‘*’ 33 times in the first row.

2)

a = "{}{:^25}{}".format('*'*4, restaurant, '*'*4)
print(a)

Here “{:^25}”.format(restaurant) formats string and create 25 length string with restaurant name in the center-aligned of the string.

3)

b = "* "+"{:<23}".format(item1)+"{:>6}".format('$'+str(item1_price))+" *"
print(b)

Here “{:<23}”.format(item1) formats string and create 23 length string with item1 value left-aligned.

and Here “{:>6}”.format(item1_price) formats string and create 6 length string with item1_price value right-aligned.

Repeat this step for item 2 and 3:

c = "* "+"{:<23}".format(item2)+"{:>6}".format('$'+str(item2_price))+" *"
print(c)

d = "* "+"{:<23}".format(item3)+"{:>6}".format('$'+str(item3_price))+" *"
print(d)

4)

print(br)

This is the end of the display.

These are python articles you like...:

  1. All Sorting Algorithm Implementation in Python
  2. Print N Rows of Pascal's Triangle in C++ and Python

Image of code:

python string formatting example code




Post a Comment

0 Comments