- How to concatenate all elements of list into string in Python
- Python concatenate list to string
- Method 1: Python concatenate list to string using for loop & plus (+) operator
- Method 2: UPython concatenate list to string using the join() method
- Method 3: Python concatenate list to string using list comprehension
- Method 4: Python concatenate list to string using the map() function
- Method 5: Python concatenate list to string using reduce() method
- Conclusion
- Как преобразовать список в строку в Python
- Преобразование с помощью цикла
- Преобразование с помощью метода join()
- Использовать выражение-генератор
- Использовать функцию map()
- Итоги
How to concatenate all elements of list into string in Python
In this Python tutorial, we will understand the implementation of Python concatenate list to string. Here we will discuss how to concatenate various list elements into a string in Python.
In Python, we can concatenate list elements into a string using the following 5 methods
- Using for loop & plus (+) operator
- Using join() method
- Using join() & list comprehension
- Using join() & map() function
- Using reduce() method
Python concatenate list to string
So, in this section, we will discuss all 5 methods to concatenate all list elements to a string in Python.
However, let us first start with the basic method of using the + operator.
Method 1: Python concatenate list to string using for loop & plus (+) operator
In this section, we will discuss the native approach to concatenating a Python list to a string.
So, in this method, first, we will use the for loop to iterate over each item given in the list. After this, we will use the + operator with the string variable and list elements to form a string using it.
Here is an example of this approach in Python.
# Defining a list usa_info = ['The', 'United States', 'is a', 'federal republic', 'consisting of', '50 states'] # Defining a empty string info = '' # Using for loop for element in usa_info: info = info + element + ' ' # Printing final string print(info)
In this example, we have defined a list containing multiple string-type values. After this, we utilized the for loop to iterate over each list element. In the last, we used the + operator to concatenate all the list elements to form a single string.
Here is the final result of the above Python program.
Output: The United States is a federal republic consisting of 50 states
Method 2: UPython concatenate list to string using the join() method
Another way to concatenate a list to a string is by using the join() method in Python. The join() method in Python is a string method that allows joining all the string elements together from a list using a given separator.
Let us see an example where we will concatenate the list elements using the join() method in Python.
# Defining a list usa_info = ['The', 'USA', 'is a country', 'located in', 'North America'] # Using join() to concatenate list to string info = ' '.join(usa_info) # Printing final string print(info)
In this example, we were joining the list elements of the usa_info list using the join() method. However, as a separator, we have used an empty string (” “).
Here is the final result of the above Python program.
Output: The USA is a country located in North America
Method 3: Python concatenate list to string using list comprehension
List comprehension in Python is a concise way to create a new list by performing some operation on each item of an existing Python list.
However, we can use this list comprehension method with the join() method to concatenate all the list elements into a string.
Here is an example of this task in Python.
# Defining a list usa_info = ['The', 'United States', 'is a', 'federal republic', 'consisting of', '50 states'] # Using join() and list comprehension info = ' '.join(str(item) for item in usa_info) # Printing final string print(info)
In the example, we utilized the list comprehension method within the join() method to get each list element. And after this, the join() method will concatenate each element together with an empty space.
After execution, we will get the following result.
Output: The United States is a federal republic consisting of 50 states
Method 4: Python concatenate list to string using the map() function
The map() is a built-in Python function that allows to execute a particular function on each element of a given iterable.
So, by using the map() function, we will convert each list element to a string data type. And then we will use the join() method to concatenate all the elements to form a single string.
# Defining a list usa_info = ['The', 'USA', 'is a country', 'located in', 'North America'] # Using join() & map() to concatenate list to string info = ' '.join(map(str, usa_info)) # Printing final string print(info)
In the example, we converted the usa_info list elements to string using the map() function. After this, we used the join() method to concatenate all list elements to a string in Python.
Here is the result of the above Python program.
Output: The USA is a country located in North America
Method 5: Python concatenate list to string using reduce() method
The reduce() is a built-in Python function that is available in the functools module. This function enables us to apply binary functions to each element of an iterable resulting in reducing the result to a single value.
Here is a method to use the reduce() function with lambda and form a single string as a result.
# Importing reduce() method from functools import reduce # Defining a list usa_info = ['America', 'is often', 'used as a', 'shorthand term', 'for the', 'USA'] # Using reduce() to concatenate list to string info = reduce(lambda element_x, element_y: element_x + ' ' + element_y, usa_info) # Printing final string print(info)
In the example, we utilized the reduce() function to concatenate list elements of the usa_info list to the info string.
Once the above Python program is executed, we will get the following result.
You may also like to read the following Python tutorials.
Conclusion
So, in this Python tutorial, we understood how Python concatenate list to string using 5 different methods. Moreover, we have also covered examples related to each method in Python.
Here is the list of methods that we discussed.
- Using for loop & plus (+) operator
- Using join() method
- Using join() & list comprehension
- Using join() & map() function
- Using reduce() method
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.
Как преобразовать список в строку в Python
Рассказываем о методе join() и других полезных инструментах для конвертирования Python‑списков в строки.
Иллюстрация: Оля Ежак для Skillbox Media
В Python существует два основных способа сделать из списка строку: с помощью цикла и с помощью метода join(). У обоих есть нюансы, о которых мы сейчас расскажем.
Преобразование с помощью цикла
Более понятный для новичка, но и более громоздкий способ перевести список в строку — воспользоваться циклом. Если вы уже знаете его и просто хотите узнать более эффективный и быстрый метод, то сразу переходите к следующему разделу. А если нет, то давайте разбираться.
Как это работает: мы создаём пустую строку, потом с помощью цикла переберём каждый элемент списка и на каждой итерации будем добавлять к строке текущий элемент списка.
lst = ['Преобразование','через','цикл'] #Создаём пустую строку string = '' #По очереди добавляем к ней каждый элемент списка for el in lst: string += el print(string) >>> Преобразованиечерезцикл
Однако такой код не будет работать, если в списке есть не только строки, но и, например, числа. Дело в том, что в Python нельзя смешивать данные разных типов.
Поэтому, перед тем как добавлять элемент в список, его нужно преобразовать в строку. Делается это с помощью функции str(). Добавим её в наш код.
#Создаём список, в котором есть как строки, так и цифры lst = ['Преобразование','через','цикл', 2] string = '' for el in lst: string += str(el) #Превращаем каждый элемент списка в строку print(string) >>> Преобразованиечерезцикл2
Если нужно установить разделитель между строками, то для него нужно прописать отдельную строчку кода внутри цикла.
lst = ['Преобразование','через','цикл', 3] string = '' for el in lst: #Добавляем к строке элемент списка string += str(el) #Добавляем к строке разделитель — в данном случае пробел string += ' ' print(string) >>> Преобразование через цикл 3
Обратите внимание: раз мы добавляем разделитель на каждой итерации, пробел будет и после цифры 3 нашего последнего элемента. Это легко проверить, если вместо пробела добавлять какой-то другой, видимый символ.
Эту проблему можно решить — ещё больше усложнив код. Например, введя условие, которое проверяет, последний это элемент в списке или нет. Однако гораздо проще и удобнее превратить список в строку, используя встроенный метод join().
Преобразование с помощью метода join()
Метод join(), по сути, делает всё то же самое, что и наш цикл, но лучше, удобнее и занимает всего одну строку. Вот как его применяют:
В качестве аргумента lst он получает список, элементы которого и будет объединять в строку, а string — это разделитель. Если мы не хотим его устанавливать, то в качестве string нужно указать пустую строку.
Посмотрим, как join() применяется на практике.
lst = ['Преобразование', 'через', 'метод', 'join()'] #Объединяем элементы списка с пустым разделителем print(''.join(lst)) >>> Преобразованиечерезметодjoin() #Устанавливаем пробел в качестве разделителя print(' '.join(lst)) >>> Преобразование через метод join()
Заметили особенность? Разделители ставятся только между элементами, а не после каждого элемента, как было в нашем цикле. join() — умница. Однако и тут есть ахиллесова пята: если в списке встречаются нестроковые элементы, мы получим ошибку. Чтобы этого избежать, надо опять-таки сначала превратить все нестроки в строки. Сделать это можно двумя способами.
Использовать выражение-генератор
Выражение-генератор — это конструкция, которая позволяет провести операцию над каждым элементом списка. Оно возвращает генератор, с которым метод join() обращается точно так же, как и со списками.
lst = [1, 1.2, 'строка', False] print(' '.join(str(el) for el in lst)) >>> 1 1.2 строка False
Конструкция str(el) for el in lst означает, что каждый элемент el в списке lst будет превращён в строку с помощью функции str (стандартной функции Python, которую мы уже использовали, когда работали с циклом).
Использовать функцию map()
Функция map() умеет делать то же самое, что и выражение-генератор, но их синтаксис отличается. В качестве первого аргумента она принимает саму операцию, в качестве второго — список, к элементам которого эта операция применяется.
lst = [1, 1.2, 'строка', False] print(' '.join(map(str, lst))) >>> 1 1.2 строка False
Конструкция map(str, lst) означает, что каждый элемент в списке lst будет превращён в строку с помощью функции str. Обратите внимание, что в качестве аргумента в map() передаётся только название функции, без скобок.
Итоги
Преобразовать список в строку можно с помощью цикла, но для этого есть и более удобный инструмент — метод join().
Если содержит нестроковые элементы, то их для начала придётся превратить в строки — иначе выскочит ошибка. Для этого можно воспользоваться выражением-генератором или функцией map().
Читайте также: