Convert List to String

 

What You'll Learn: In this tutorial, you'll discover how to convert a list of items to a string in Python using the String.join() method. This is like taking pieces of a puzzle and joining them into a complete picture!

Using the join() Method

The String.join(iterator) method takes an iterable like a list and returns a string created by joining the items with the calling string as a separator.

Syntax:

python
separator_string.join(myList)

If any items in the list are not strings, use the map(str, iterator) function to convert all items to strings.

Syntax with map():

python
separator_string.join(map(str, myList))

Examples

  1. Convert a List to CSV String

    • Let's take a list of strings and convert it to a string with commas separating the items.

    Example Code:

    python
    items = ["apple", "banana", "cherry"]
    output = ",".join(map(str, items))
    print(output)
    

    Output: apple,banana,cherry
     

  2. Convert a List to a String with Spaces

    • Convert a list of items to a string with spaces separating the items.

    Example Code:

    python
    items = ["apple", "banana", "cherry"]
    output = " ".join(map(str, items))
    print(output)
    

    Output: apple banana cherry
     

  3. Convert a List of Different Data Types to a String

    • Convert a list containing strings, numbers, and other data types to a string.

    Example Code:

    python
    items = ["apple", "banana", "cherry", 20, True, 3.14]
    output = ",".join(map(str, items))
    print(output)
    

    Output: apple,banana,cherry,20,True,3.14
     

Try It Yourself: Fun Exercises

  1. Favorite Foods:
    • Create a list of your favorite foods.
    • Convert the list to a string with each food separated by a comma.
  2. Daily Routine:
    • Make a list of your daily activities.
    • Convert the list to a string with activities separated by a space.

Summary:

In this Python tutorial, we learned how to convert a list of items to a string using the join() method and map() function. This method is useful for transforming lists into a single, readable string. Keep experimenting and have fun with lists in Python!