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!

 
 

Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

FacebookTwitterLinkedinLinkedin
knowledge base

Python Classes