Python – using format in strings


Inside the string, we can specify both fixed text and part of the text defined by the format function, which will consist of separately specified sections:

print(“This cat has {0} kittens and a {1}”.format(2,”tail”))

Instead of using numbers inside curly braces, you can immediately set the value of the variable in them – a,b,c:

print(‘quantity: ({a}, {b}, {c})’.format(a=5,b=2,c=4))

Inside curly braces, both ordinal indexing and setting variables can be combined:

print(“This {animal} has {0} kittens”.format(2, animal=’cat’))

If we want to shift characters to the right or left, this is done through the function {:<20}.format(“string”) – inside the curly braces, the colon means “from the beginning” / “to the end”, >/< indicates where the shift to the right goes or to the left, and the description inside the brackets after .format shows what we are dealing with (string, text, hello, etc.). This function creates a shift – tabs, spaces.

print(‘{:<15}’.format(“Kitten”))
Kitten #result

print(‘{:>15}’.format(“Kitten”))
Kitten #result

The .format function can be used with binary numbers:

print(‘{:b}‘.format(11))
1011 #result is 11 in binary

Using the .format function with a hexadecimal number system (Hexadecimal):

print(‘{:x}‘.format(11))
b #result is 11 in hexadecimal

Using the .format function with octal number system (Octal):

print(‘{:o}‘.format(11))
13 #result is 11 in octal


This entry was posted in Python (en). Bookmark the permalink.

Leave a Reply

🇬🇧 Attention! Comments with URLs/email are not allowed.
🇷🇺 Комментарии со ссылками/email удаляются автоматически.