Site icon Meccanismo Complesso

Python Lessons – 5.7 String formatting

Python Lessons - 5.7 String formatting m
Python Lessons - 5.7 String formatting

String Formatting

So far we have seen some methods for combining strings with non-string values, converting them to strings. Actually there is a much more efficient way to add non-string values to strings.

A string is defined in the classic method, but inserting increasing integers enclosed in braces {}. Then the same string is referenced together with its format() method, in which each argument will replace the numbers between the brackets {i} staples in the string.

num1 = 12
num2 = 24
msg = "The number {0} is half of {1}".format(num1, num2)
print(msg) 

If you run it, you get

>>>
The number 12 is half of 24

Reference values can be used instead of integers between the braces.

msg = "The number {num1} is half of {num2}".format(num1=12, num2=24)
print(msg)

If you run it, you get:

>>>
The number 12 is half of 24

⇐ Go to Python Lesson 5.6 – List comprehension

Go to Python Lesson 5.8 – Some useful functions for numbers and strings ⇒

Exit mobile version