String Formatting in Python

String formatting is a way of embedding non-strings within strings. In order to do that you use the format method.

Example:

nums = [56, 81, 13]
print(nums)
msg = "Numbers: {0} {1} {2}". format(nums[0], nums[1], nums[2])
print(msg)

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
[56, 81, 13]
Numbers: 56 81 13
ddn_ro@linux:~/Desktop$

Each argument of the format function is placed in the string at the corresponding position, which is determined using the curly braces { }.

String formatting can also be done with named arguments.

Example:

my_bike = "{Honda}, {Yamaha}, {Suzuki}".format(Honda=2500, Yamaha=2000, Suzuki=1700)
print(my_bike)

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
2500, 2000, 1700
ddn_ro@linux:~/Desktop$

Leave a Reply