Join a list of strings wrapping each string in quotes in Python

avatar

Borislav Hadzhiev

Last updated: Jun 18, 2022

banner

Check out my new book

Join a list of strings wrapping each string in quotes in Python #

To join a list of strings wrapping each string in quotes:

  1. Call the join() method on a string separator.
  2. Pass a generator expression to the join() method.
  3. On each iteration, use a formatted string literal to wrap the item in quotes.
main.py
my_list = ['one', 'two', 'three'] my_str = ', '.join(f'"{item}"' for item in my_list) print(my_str) # 👉️ '"one", "two", "three"'

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

main.py
my_list = ['one', 'two', 'three'] print(', '.join(my_list)) # 👉️ 'one, two, three'

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

main.py
my_list = ['one', 'two', 'three'] my_str = ' '.join(f'"{item}"' for item in my_list) print(my_str) # 👉️ '"one" "two" "three"'

If you don't need a separator and just want to join the iterable's elements into a string, call the join() method on an empty string.

We used a formatted string literal to wrap each list item in quotes.

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}.

The last step is to use a generator expression to iterate over the list of strings.

main.py
my_list = ['one', 'two', 'three'] my_str = ', '.join(f'"{item}"' for item in my_list) print(my_str) # 👉️ '"one", "two", "three"'
Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

In the example, we iterated over the list and wrapped each item with quotes.

This approach also works if the list contains values of different types (e.g. integers).

main.py
my_list = ['one', 'two', 'three', 4, 5] my_str = ', '.join(f'"{item}"' for item in my_list) print(my_str) # 👉️ '"one", "two", "three", "4", "5"'

The join() method raises a TypeError if there are any non-string values in the iterable, but we take care of converting each list item to a string with the f-string.

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.