String Formatting Methods in Python | Learn Python From Scratch 6 | Kovolff

preview_player
Показать описание
Let us start off with a simple string

abc = 'hello John, your car costs 15239.45 and has 55000 km on it'

Now everything in this string remains the same, except John, 15239.45 and 55000 might change everytime we call the string abc

Let us thus create variables for those variable elements in the string
your_name = 'john'
car_price = 15239.45782
car_km = 55000

There three ways to format our abc string.
Option 1:
abc = 'hello {}, your car costs {} and has {} km on it'.format(your_name, car_price, car_km)

We insert {} as placeholders for those variable elements in the string.
Then we add .format() and within the parentheses of this format method we insert the three values or variables for these placeholders

Note that having more placeholders than values within .format() throws an error

Option 2:
abc = 'hello {0}, your car costs {1} and has {2} km on it'.format(your_name, car_price, car_km)

We insert an index in each placeholder, so Python knows which element out of the .format() list to insert. With this option the ordering of the variable elements in the string depends on the index number and not on the position of the variable elements within .format()

Option 3:
abc = 'hello {name}, your car costs {price} and has {km} km on it'.format(name=your_name, price=car_price, km=car_km)

We insert a keyword in each placeholder, and in .format() we assign each variable or value to its key

abc = 'hello {name}, your car costs {price:.2f} and has {km} km on it'.format(name=your_name, price=car_price, km=car_km)

:.2f in the price placeholder rounds the prices to 2 decimal places.

The .format() method has a myriad of options, which we will visit from time to time in our journey towards developing our unit converter.

#python #strings #format
Рекомендации по теме
welcome to shbcf.ru