How to Use a List to Format a String in Python
The format() method allows you to create a formatted string by using data stored in a list.
Example
Let’s start by creating a list with three elements:
lista = ['Italy', 'Rome', 'Europe']
Next, we'll create a string that includes placeholders referencing the list using the format() function.
stringa = "The capital of {0[0]} is {0[1]}. It’s located in {0[2]}.".format(lista)
The format() function accesses the list and replaces the placeholders with the corresponding values from the list.
- {0[0]} = Italy
- {0[1]} = Rome
- {0[2]} = Europe
Finally, we'll print the formatted string using the print() function:
print(stringa)
The output will be:
The capital of Italy is Rome. It’s located in Europe.
And there you have it!