String formatting in a list comprehension in Python

avatar

Borislav Hadzhiev

Last updated: Aug 30, 2022

banner

Photo from Unsplash

String formatting in a list comprehension in Python #

To use string formatting in a list comprehension:

  1. Use a list comprehension to iterate over the list.
  2. Use a formatted string literal to format each item in the list.
  3. The new list will contain the formatted strings.
main.py
my_list = [2, 4, 6] # ✅ string formatting in a list comprehension result = [f'num: {item}' for item in my_list] print(result) # 👉️ ['num: 2', 'num: 4', 'num: 6'] # --------------------------------------- # ✅ join the items in a list with a separator result = ','.join(str(item) for item in my_list) print(result) # 👉️ 2,4,6 # --------------------------------------- # ✅ string formatting using str.format() result = '{},{},{}'.format(*my_list) print(result) # 👉️ 2,4,6 # --------------------------------------- # ✅ string formatting with a list of lists or list of tuples my_list = [[1, 2], [3, 4], [5, 6]] result = ' '.join( f'coords={",".join(str(item) for item in sublist)}' for sublist in my_list) print(result) # 👉️ coords=1,2 coords=3,4 coords=5,6

The first example uses an f-string to format the strings in the list.

main.py
my_list = [2, 4, 6] result = [f'num: {item}' for item in my_list] print(result) # 👉️ ['num: 2', 'num: 4', 'num: 6']

We used a list comprehension to iterate over the list.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we use a formatted string literal to format the current item.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

main.py
my_str = 'is subscribed:' my_bool = True result = f'{my_str} {my_bool}' print(result) # 👉️ is subscribed: True

Make sure to wrap expressions in curly braces - {expression}.

If you need to join the items in a list with a separator, use the str.join() method.

main.py
my_list = [2, 4, 6] result = ','.join(str(item) for item in my_list) print(result) # 👉️ 2,4,6

If you have a list of strings, you can pass the list directly to the str.join() method.

main.py
my_list = ['a', 'b', 'c'] result = ','.join(my_list) print(result) # 👉️ 'a,b,c'

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

Note that the method raises a TypeError if there are any non-string values in the iterable.

The string the method is called on is used as the separator between the elements.

If you have a list of lists or a list of tuples, use 2 calls to the str.join() method.

main.py
my_list = [[1, 2], [3, 4], [5, 6]] result = ' '.join( f'coords={",".join(str(item) for item in sublist)}' for sublist in my_list) print(result) # 👉️ coords=1,2 coords=3,4 coords=5,6

If your sublists contain strings, the operation is a bit simpler.

main.py
my_list = [['a', 'b'], ['c', 'd'], ['e', 'f']] result = ' '.join( f'coords={",".join(sublist)}' for sublist in my_list) print(result) # 👉️ coords=a,b coords=c,d coords=e,f
Make sure to alternate between single and double quotes to avoid terminating the f-string prematurely.

The nested call to the join() method joins the items in each sublist with a comma separator.

The items in the generator object are then joined into a string with a space separator.

You can change the separators and the contents of the f-string depending on your use case.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.