Future-Proof Your Career, Master Data Skills + AI

Blog

Future-Proof Your Career, Master Data Skills + AI

Blog

How to Convert List to String in Python: User Guide + Examples

by | 2:21 pm EST | December 06, 2023 | Python

Converting a list into a string is a great way to display its contents in a clear, readable, and user-friendly format! So, how can you convert this Python data structure into a string?

The easiest way to convert a list into a string in Python is to use the built-in join() methods. You can take care of edge cases like non-string data types by combining this method with a list comprehension.

You can also convert a Python list to a string by using a for loop to join all the string’s items.

Throughout this article, you will learn how to utilize these built-in capabilities to convert lists to strings quickly and easily. We will also provide some great examples to ensure that the concepts you’re learning are well-illustrated.

So, let’s get started!

How to Convert List to String in Python

What is a Python List?

In the Python programming language, a list is a mutable, heterogeneous, and ordered collection of items. Mutable means you can modify the contents of a list after it is created.

Heterogeneous implies that a list can store different types of data, such as integers, strings, and even other lists. It differs from an array in this respect as arrays can only store one datatype.

To create a Python list, simply enclose elements within square brackets [] and separate them with commas. For example:

my_list = ["apple", 1, 3.14, True]

You can access and modify these elements using a feature called Indexing. To access an element, use the square brackets [] with the index number. Python lists use zero-based indexing so the first element has an index of 0 instead of 1.

For example:

my_list = [1, 2, 3, 4, 5]
element = my_list[2]
last_element = my_list[-1] 

print(element)
print(last_element)

Output:

Negative indexing example

In the example above, we accessed the third and last element in the list using the indexes 2 and -1. Remember, negative indexing allows you to access elements from the end of the list.

What is a Python String?

Python strings are essentially ordered sequences of characters. They play a vital role in handling text data and can be created by enclosing text in different types of quotes, either single (‘ ‘) or double (” “). You can also use triple quotes (”’ ”’ or “””) to create strings that span multiple lines.

They can be assigned to variables just like integers or floats. For example:

text = "Hello, world!"
print(text)

Output:

Hello, world!

Characters in Python strings can be accessed using their index positions the same way we can access objects in a list. Remember that Python uses zero-based indexing, which means the first character has an index of 0.

Finally, Python strings are immutable, meaning that they cannot be changed after they are created. If you want to modify a string via string operations like slicing, you will have to create a new string.

How to Convert a List to a String in Python

Using The .join() Method

The join() method is a powerful and efficient way to convert a list of strings into a single string. You can use this method to connect string elements in a list while adding a separator, also known as a delimiter, between each element.

To use the join() method, first, you need to create a separator, which is often an empty string or a character that you want to use as a delimiter between the list elements. It’s important to note that the separator must be a string.

Next, call the join() method on it with your list of strings as an argument. Here’s an example:

words = ['this', 'is', 'a', 'sentence']
separator = ' '
combined_string = separator.join(words)

print(combined_string) 

Output:

Negative indexing example

In this python program, the separator is a space character ‘ ‘, and the words list is the list of strings you want to combine. Calling the .join() method combines the list into a string “this is a sentence”.

You can use different separators to join the elements in your list. For instance, using a comma as a separator will create a comma-separated string:

numbers = ['1', '2', '3', '4']
separator = ','
combined_string = separator.join(numbers)
print(combined_string) 

Output:

1,2,3,4

Can I use the join() method with a list containing multiple data types?

No, you cannot. The join() method is versatile and can handle various use cases. However, it only works when the list contains only strings. If it contains other data types like booleans or integers, the join method will return a TypeError.

For example:

words = ['this', 9, True , 77]
combined_string = ' '.join(words)

print(combined_string) 

Output:

TypeError when joining

We can solve this problem by converting all the elements into strings before joining them. We’ll be discussing two ways to do this in the next two sections.

Using List Comprehension

List comprehensions are a great tool that you can use to convert all the elements in your list to a string before joining them. You can use this tool in conjunction with the str method to go over each item in the list and convert it into a Python string.

Let’s fix our earlier example:

words = ['this', 9, True , 77]
combined_string = ' '.join([str(word) for word in words])

print(combined_string) 

Output:

List Comprehension to convert the list element to the same data type

Now, the TypeEror in the example is gone thanks to the str method. The list comprehension converts all of them into a string data type. Next, the join method combines them to form the final string.

Using the Map() Function

The map function is another tool you can use to ensure that all the variables in your list are string values before converting them. The map() function requires a function and an iterable as its two arguments.

The first argument is a function that will be applied to each element in the iterable while the second argument is the iterable itself.

To use it, you have to pass in the str() function and your list into the map() function as arguments.

The map() function will apply the str() function to each element in the list and return an iterable object. To obtain a list as the final result, surround the iterable object with the list() constructor. Let’s look at an example:

words = ['this', 9, True , 77]
combined_string = ' '.join(list(map(str, words)))

print(combined_string) 

Output:

this 9 True 77

Note: The map() function works not only with str() but also with other functions. For instance, you can use it with custom functions or lambda functions. Furthermore, you can apply it to different iterable objects, such as lists, tuples, and other sequence data types.

Using a For Loop

You can use a simple for loop to combine all the elements in your list into a string. The loop will iterate through the list and add each item to the string. Let’s look at an example:

def for_combine(list):
   final_string = ''
   for item in list:
        final_string += str(item) + ' '
    return final_string

print(for_combine(["Every", "item", "is", "joined", "together"]))

Output:

Every item is joined together

As we can see, it adds all the elements together and separates them with a space.

Using the Enumerate Function

The enumerate function can also be used to combine all the elements in a list into a string. It is particularly helpful when you need both the contents of the list and their positions on the list. Here’s an example:

def enum_combine(list):
   final_string = ''
   for i, item in enumerate(list):
        final_string += f'Item {i}: {item}. n'
   return final_string

print(enum_combine(["Apple", "Croissant", "Jam", "Cheese"]))

Output:

Enumerate function

In the above code, we returned each item on the list with its position inside a single string thanks to the enum function.

Using the str.format() Method

The str.format() method is a great way to convert items in a list to a string, especially if the information in the list is structured.

For example, if you know the number of items in the list and the position of each important item, you can easily use this method to convert it to a string.

Here’s an example:

poem = ["Green", "eggs","and","ham" ]

result = "{} {} {} {}.".format(*poem)

Output:

Green eggs and ham.

In the example above, we deconstructed the list using the * operator. Then, we used the .format method to place each value in the list inside the tring.

Final Thoughts

Knowing how to convert lists to strings in Python is a fundamental skill for any programmer.

Whether you opt for the join() method, list comprehension, or a for loop, understanding these techniques will enable you to properly manipulate and handle data in your applications.

So, learn and practice them to enhance your coding proficiency and unlock new possibilities in your Python projects!

You can also check out this video on 12 Data Wrangling Functions In Python That You Should Know to upgrade your data manipulation skills.

Frequently Asked Questions

What is the best way to print a list of strings in Python as a single string?

To print a list of strings as a single string in Python, you can use the for loop in conjunction with the print method.

str_list = ["Welcome", "to", "our", "home."]
for word in str_list:
    print(word, end = " ")

Output:

Printing out a list in Python

In the end argument, we specify a space character as the delimiter between each element.

How to concatenate a list of strings in Python with spaces?

To concatenate a list of strings in Python with spaces, use the join() method with a space character as the delimiter:

words = ['Hello', 'world']
result = ' '.join(words)
print(result)

Output:

Hello world

What method should I use to change a list of lists to a string in Python?

To change a list of lists to a string, you can use a nested list comprehension and the join() method. For example, you can create a string with each list element separated by a comma and each list itself separated by a semicolon:

list_of_lists = [['a', 'b'], ['c', 'd'], ['e', 'f']]
result = '; '.join([', '.join(sublist) for sublist in list_of_lists])
print(result)

Output:

a, b; c, d; e, f

Is there a way to convert a list to a string in Python without spaces in between them?

Yes, you can convert a list to a string without any spaces by using an empty string as a delimiter. Here’s an example:

my_list = ['apple', 'banana', 'cherry']
result = ''
result = del.join(my_list)
print(result)  

Output:

applebananacherry

How to convert a list of integers into a single integer?

You can convert a list of integers into a single integer by using the join() method. However, since you’re converting integers, you’re going to have to convert the integers into strings before joining and convert them back after joining. Let’s see how this works:

def convert_int_list(li):
    str_li = ''.join([str(l) for l in li])
    return int(str_li)

print(convert_int_list([12, 78, 90]))

Output:

127890

So, if we pass a list filled with integers into the function, it will join them and return a single integer.

How to split a string into a list?

We can split a string into a list by using the split() function. Inside the function, we can specify any separator for splitting the list. The default separator is whitespace, but you can specify a variety of delimiters like commas, letters, etc.

big_str = 'We are going on an adventure!'
str_li = big_str.split()

print(str_li)

Output:

['We', 'are', 'going', 'on', 'an', 'adventure!']

Related Posts