RUVIDEO
Поделитесь видео 🙏

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

📁 Обучение 👁️ 22 📅 03.12.2023

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

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «String Formatting Methods in Python | Learn Python From Scratch 6 | Kovolff», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.