Python list to string function

Convert a List to String in Python

In this tutorial, you can quickly discover the most efficient methods to convert Python List to String. Several examples are provided to help for clear understanding.

Python provides a magical join() method that takes a sequence and converts it to a string. The list can contain any of the following object types: Strings, Characters, Numbers.

While programming, you may face many scenarios where list to string conversion is required. Let’s now see how can we use the join() method in such different cases.

How to Convert Python List to String

As we’ve told above that Python Join() function can easily convert a list to string so let’s first check out its syntax.

Читайте также:  Plotting colors in python

Python Join() Syntax

The syntax of join() is as follows:

Convert Python List of Strings to a string using join()

Let’s say we have a list of month names.

# List of month names listOfmonths = ["Jan" , "Feb", "Mar", "April", "May", "Jun", "Jul"]

Now, we’ll join all the strings in the above list considering space as a separator.

Scenario#1: Jan Feb Mar April May Jun Jul Scenario#2: Jan, Feb, Mar, April, May, Jun, Jul

Convert a list of chars into a string

With the help of join() method, we can also convert a list of characters to a string. See the example given below:

charList = ['p','y','t','h','o','n',' ','p','r','o','g','r','a','m','m','i','n','g'] # Let's convert charList to a string. finalString = ''.join(charList) print(charList) print(finalString)

Let’s assume that we have got a list of some numbers and strings. Since it is a combination of different objects, so we need to handle it a little differently.

sourceList = ["I" , "got", 60, "in", "Science", 70, "in", "English",", and", 66, "in", "Maths"]

It is not possible to use the join() function on this list. We first have to convert each element to a string to form a new one, and then only we can call join() method.

# Let's convert sourceList to a list of strings and then join its elements. stringList = ' '.join([str(item) for item in sourceList ])

The final string would appear something like:

sourceList = ["I" , "got", 60, "in", "Science,", 70, "in", "English,", "and", 66, "in", "Maths."] # Let's convert sourceList to a list of strings and then join its elements. stringList = ' '.join([str(item) for item in sourceList ]) print(stringList)

Get a comma-separated string from a list of numbers

If you simply wish to convert a comma-separated string, then try the below shortcut:

print (', '.join(map(str, numList)))

We can even use the new line character (‘\n’) as a separator. See below:

print ('\n'.join(map(str, numList)))

Источник

6 Ways to Convert a Python List to a String

Learn How to Convert a List to String in Python Cover Image

In this tutorial, you’ll learn how to use Python to convert (or join) a list to a string. Using Python to convert a list to a string is a very common task you’ll encounter. There are many different ways in which you can tackle this problem and you’ll learn the pros and cons of each of these approaches.

By the end of this tutorial, you’ll have learned:

  • How to use the .join() method to convert a Python list to a string
  • How to use the map() function to convert a Python list to a string
  • How to work with heterogenous lists when converting a list to a string
  • How to use for loops and list comprehensions to convert a Python list to a string
  • What method is the fastest when joining a list to a string

A Brief Refresher on Python Lists and Strings

Python lists are container data types that have a number of important attributes. Python lists are:

  1. Ordered, meaning that items maintain their order
  2. Indexable, meaning that items can be selected based on their position
  3. Mutable, meaning that we can modify lists
  4. Heterogenous, meaning that they can contain different types of objects (more on that shortly!)

Python lists are created by placing items into square brackets, separated by commas. Let’s take a look at how we can create a list:

# Creating a Sample List a_list = ['Welcome', 'to', 'datagy.io']

In the code block above, we created a sample list that contains strings.

Python strings, on the other hand, are created using single, double, or triple quotes. Unlike Python lists, strings are immutable. However, they are ordered and indexable!

Let’s create a sample string in Python:

# Creating a Sample String a_string = 'Welcome to datagy.io'

We can see that the list and the string contain the same set of English words. In this tutorial, you’ll learn how to convert the list of values into a broader string.

Using .join() to Convert a List to a String in Python

Python strings have many methods that can be applied to them. One of these methods is the .join() method, which allows you to use a string as a concatenation character to join a list of values.

The string to which we apply the .join() method represents the character (or characters) that will exist between each item in a list.

Let’s see how we can use Python’s .join() method to convert a list to a string:

# Using .join() to Convert a List to a String a_list = ['Welcome', 'to', 'datagy.io'] a_string = ''.join(a_list) print(a_string) # Returns: Welcometodatagy.io

Let’s break down what we did in the code above:

  1. We declared our list of strings, a_list
  2. We then created a new variable a_string , which is the result of applying the .join() method to an empty string » and passing in our list of values

We can see that this returned the concatenated string without any spaces in between!

If we wanted to separate the strings using a character, such as a space, we can simply apply the .join() method to a string containing that character!

# Using .join() to Convert a List to a String a_list = ['Welcome', 'to', 'datagy.io'] a_string = ' '.join(a_list) print(a_string) # Returns: Welcome to datagy.io

In the code block above, we modified the string we’re applying the method to from an empty string to one that contains only a space, ‘ ‘ .

Problems with Using .join() To Convert a List to a String in Python

The .join() method expects that all elements in the list are strings. If any of the elements isn’t a string, the method will raise a TypeError , alerting the user that a string was expected.

Let’s see what this looks like:

# Raising a Type Error When Using the .join() Method a_list = ['Welcome', 'to', 'datagy.io', 1] a_string = ' '.join(a_list) print(a_string) # Raises: TypeError: sequence item 3: expected str instance, int found

In the following sections, you’ll learn how to resolve this error.

Using map() to Convert a List to a String in Python

The map() function allows you to map an entire list of values to another function. This allows you to easily work with heterogenous lists (as we did above). By doing this, we can prevent any TypeErrors from being raised if there are non-string data types.

To learn more about the map() function in Python, check out my in-depth guide. Let’s see how we can use the map() function with the .join() method to convert a list to a string:

# Using map() with .join() to Convert a List to a String a_list = ['Welcome', 'to', 'datagy.io', 1] # Option 1: mapped = map(str, a_list) a_string = ' '.join(mapped) # Option 2: a_string = ' '.join(map(str, a_list)) print(a_string) # Returns: Welcome to datagy.io 1

Let’s break down what we did in the code block above:

  1. We created a list that contains both strings and an integer
  2. In Option 1 (which works the same way, though a bit more verbose), we created a new mapping object
  3. The mapping object, mapped , uses the map() function and takes the callable of the function we want to map each element of our list to
  4. We then pass that new map object to the .join() method which concatenates the list to a string

In the following section, you’ll learn how to use a for-loop to convert a list to a string.

Using a For Loop to Convert a List to a String in Python

Using a for loop allows you to iterate over each item in a list and append it to a new string. This means that you can easily concatenate a list of values to a string.

Using a For Loop with Lists of Only Strings

Let’s take a look at how this works when working with lists that contain only strings:

# Using a Python for loop to Convert a List to a String in Python a_list = ['Welcome', 'to', 'datagy.io'] a_string = '' for item in a_list: a_string += item print(a_string) # Returns: Welcometodatagy.io

Using a For Loop with Heterogenous Lists

Similar to our previous example, this will raise a TypeError if we attempt to concatenate non-string values. In order to fix this error, we can either:

  1. Check if the item is a string and, if not, convert it
  2. Apply the str() function to each item in the list

Let’s see how we can use the second option, as it requires less code:

# Using a Python for loop to Convert a Heterogenous List to a String in Python a_list = ['Welcome', 'to', 'datagy.io', 1] a_string = '' for item in a_list: a_string += str(item) print(a_string) # Returns: Welcometodatagy.io1

Using a For Loop with a Separator to Concatenate a List to a String

One thing you’ll notice is that we are simply concatenating the items without any separator. We can also include a separator in the for-loop, in order to make our text cleaner.

Let’s see how we can separate each item with a space in order to make our text cleaner:

# Concatenating a List to a String in Python Using a Separator a_list = ['Welcome', 'to', 'datagy.io', 1] a_string = '' for item in a_list: a_string = a_string + ' ' + str(item) a_string = a_string.strip() print(a_string) # Returns: Welcome to datagy.io 1

Let’s break down what we did in the code block above:

  1. We declared our list and empty string
  2. We then looped over each item and appended a space and the string representation of each item to the string
  3. We then applied the .strip() method to our final string, in order to remove a resulting leading space

In the following section, you’ll learn how to use a list comprehension to concatenate a list to a string.

Using a List Comprehension to Convert a List to a String in Python

We can also easily use a list comprehension in combination with the .join() method to convert a list to a string. This allows us to work with lists that contain non-string data types.

Remember, when we attempt to use the .join() method with lists that contain non-string data types, we raise a TypeError . We can resolve this error by first converting each item in the list to a string, by using the str() function within a list comprehension. Let’s see what this looks like:

# Using .join() With Mixed Data Types a_list = ['Welcome', 'to', 'datagy.io', 1] comp = [str(item) for item in a_list] a_string = ' '.join(comp) print(a_string) # Returns: Welcome to datagy.io 1

In the code block above, we used a list comprehension to create a string copy of each item in the list. We then passed this new list into our .join() method call.

Using a list comprehension is a clean and fast way to modify items in a list.

What is the Fastest Way to Convert a List to a String in Python?

In this section, we’ll explore what the fastest method to convert a Python list to a string is in Python. In order to test this, we’ll load a list of twenty million elements and convert it to a string.

In the first round of tests, we’ll use a heterogenous list which requires converting the items to strings and then combining them into a resulting string. These tests are more likely to occur since you can’t often guarantee each item will be a string:

Источник

Оцените статью