- Concatenate items in a List to a String
- What are Strings and List ?
- Frequently Asked:
- Concatenate items in a list to a string using For Loop
- Concatenate items in a list to a string using join()
- Concatenate items in a list to a string using map() method :
- Concatenate items in a list to a string using reduce()
- Related posts:
- How to concatenate all items in a list in Python
- Syntax
- Parameters
- Return value
- Code example
- Concatenate strings in Python (+ operator, join, etc.)
- Concatenate multiple strings: + , +=
- The + operator
- The += operator
- Concatenate consecutive string literals
- Concatenate strings and numbers: + , += , str() , format() , f-string
- The + and += operators and str()
- format() and f-string
- Join a list of strings into one string: join()
- Join a list of numbers into one string: join() , str()
Concatenate items in a List to a String
In this article, you will learn to concatenate items in list to a single string object in Python.
Table Of Contents
What are Strings and List ?
A String in python is an array of bytes representing Unicode characters enclosed in single, double or triple quotes.
Frequently Asked:
A List in Python is a kind of container enclosed in a square bracket that can hold data of any data type like integers or string etc. For better understanding, consider that list in python is simmilar to an array in other programming languages but here is one big difference i.e. – An array in other programming language stores similar kind of data type but a list can store elements of mixed data types. Therefore it is also known as Heterogeneous List.
Major difference between a list and a string is that a list is an ordered sequence of differet kinds of objects and a string is an ordered sequence of characters.
Now we will look some of the methods through which we can concatenate items in a list to a single string.
Always try examples in your machine.Just copy and paste code and play around with it. Also i have used Python 3.10.1 for writing example codes. To check your version write python –version in your terminal.
Concatenate items in a list to a string using For Loop
For loop in python is used to iterate over elements of a given sequence type (list or tuple etc). Here we will initialize an empty string and add elements of list after iterating over it. Keep in mind it can cannot concatenate a Heterogeneous List, because it will throw a TypeError. It only concatenates a list of strings to a string.
listOfStrs = ['Concatenating', 'using', 'Loop'] strValue = '' # Concatenate strings in a list to a single string for elem in listOfStrs: sep = ' ' if len(strValue) > 0 else '' strValue = strValue + sep + elem print(strValue)
Here you can see elements of list has been concatenated into a single string.
Concatenate items in a list to a string using join()
The join() method is a built in python function which takes only one parameter, that is an iterable. It joins all elements in this iterable to a string.We can use this to Concatenate all elements in a list to a string.
listOfStrs = ['Concatenating','using','join','method'] # Concatenate strings in a list to a single string strValue = ' '.join(listOfStrs) print(strValue)
Concatenating using join method
Here you can see items in listOfStrs has been concatenated into a string using the join() method.
Concatenate items in a list to a string using map() method :
The map() is a built-in function of Python, and it is used to apply a function to each time in an iterable. It recieves two parameters i.e. a function and an iterable.
Using map() function becomes very useful when we have either Heterogeneous list or a list of integers.
Here map() function will get two arguments –
– str() function : The str() function will convert the given data into string.
– A list, which we want to convert into a string.
At last we will use the join() function to combine the returned data from above function. This method is combination of various methods like str(), join() , map(), but can be most useful method.
listOfValues = ["Highest","Score","Of","MSD","is",183,"in","ODI","cricket"] strValue = ' '.join(map(str, listOfValues)) print(strValue)
Highest Score Of MSD is 183 in ODI cricket
Here you can see items of heterogenous list(listOfValues) has been concatenated into a string variable(strValue) using map() and there is not any kind of Error.
Concatenate items in a list to a string using reduce()
Apply str() function on each element of list to convert them to string. Then pass that sequence to reduce() function along with a lambda function that will concatenate the strings.
For Example
from functools import reduce listOfValues = ["Highest", "Score", "Of", "MSD", "is", 183, "in", "ODI", "cricket"] # Concatenate all items in list to a string strValue = reduce(lambda x,y: x + ' ' + y, map(str, listOfValues) ) print(strValue)
Highest Score Of MSD is 183 in ODI cricket
So we have seen three different methods through which we can concatenate items in a list to a single string. Most easiest method is join() method and most practical and useful method is map() method because there is no barrier of using only one kind of data. You can use int or combination of string,int and float. You cannot use any other data type in other two methods because it will genarate a TypeError. Like you can see in the example below.
ex_lst = ["Highest","Score","Of","MSD","is",183,"in","ODI","cricket"] ex_str = ' '.join(ex_lst) print(ex_str)
ex_str = ' '.join(ex_lst) TypeError: sequence item 5: expected str instance, int found
Thanks and Happy Learning.
Related posts:
How to concatenate all items in a list in Python
Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.
Python provides a range of modules and functions. Lists are structures used to store multiple items. They are one of four structures used to hold data in Python, the others being tuples, sets, and dictionaries. Lists can store items of any data type, allowing items of different data types to be in the same list. They can hold data in any order, and duplicates are stored separately. To concatenate a list of strings, use the join() method with a separator string.
Syntax
Parameters
- string : The specified separator; this is required. The separator is added between the items that are being concatenated.
- iterable : An iterable that only has items of data type string. Any other data type will result in an error. This parameter is required.
Return value
The join method returns a string that contains all items of the iterable, separated by the specified string .
For example, if we want to concatenate the items of the list [‘i’, ‘love’, ‘cats’] with the separator ‘-’, our output will be i-love-cats .
Code example
In the code below, we concatenate the items of three lists with different separators.
#initialize the listslist1=["cat", "dog", "mouse", "bird"]list2=["i", "am", "16", "years", "old"]list3=["1", "2", "3", "4", "5", "6"]#concatenate the listsstring1=' '.join(list1)string2='-'.join(list2)string3='#'.join(list3)#print the concatenated stringsprint(string1)print(string2)print(string3)
Learn in-demand tech skills in half the time
Concatenate strings in Python (+ operator, join, etc.)
This article explains how to concatenate strings or a list of strings in Python.
Concatenate multiple strings: + , +=
The + operator
You can concatenate string literals ( ‘. ‘ or «. » ) and string variables with the + operator.
s = 'aaa' + 'bbb' + 'ccc' print(s) # aaabbbccc s1 = 'aaa' s2 = 'bbb' s3 = 'ccc' s = s1 + s2 + s3 print(s) # aaabbbccc s = s1 + s2 + s3 + 'ddd' print(s) # aaabbbcccddd
The += operator
You can append a string to an existing string with the += operator. The string on the right is concatenated after the string variable on the left.
s1 = 'aaa' s2 = 'bbb' s1 += s2 print(s1) # aaabbb s = 'aaa' s += 'xxx' print(s) # aaaxxx
Concatenate consecutive string literals
If you write string literals consecutively, they are automatically concatenated.
s = 'aaa''bbb''ccc' print(s) # aaabbbccc
Even if multiple spaces, newlines, or backslashes \ (used as continuation lines) are present between the strings, they will still be concatenated.
s = 'aaa' 'bbb' 'ccc' print(s) # aaabbbccc s = 'aaa'\ 'bbb'\ 'ccc' print(s) # aaabbbccc
This approach can be handy when you need to write long strings over multiple lines of code.
Note that this automatic concatenation cannot be applied to string variables.
# s = s1 s2 s3 # SyntaxError: invalid syntax
Concatenate strings and numbers: + , += , str() , format() , f-string
The + and += operators and str()
The + operation between different types results in an error.
s1 = 'aaa' s2 = 'bbb' i = 100 f = 0.25 # s = s1 + i # TypeError: must be str, not int
To concatenate a string and a number, such as an integer int or a floating point number float , you first need to convert the number to a string with str() . Then, you can use the + or += operator to concatenate.
s = s1 + '_' + str(i) + '_' + s2 + '_' + str(f) print(s) # aaa_100_bbb_0.25
format() and f-string
If you need to adjust the format, such as zero-padding or decimal places, the format() function or the str.format() method can be used.
s1 = 'aaa' s2 = 'bbb' i = 100 f = 0.25 s = s1 + '_' + format(i, '05') + '_' + s2 + '_' + format(f, '.5f') print(s) # aaa_00100_bbb_0.25000 s = '<>_ _<>_ '.format(s1, i, s2, f) print(s) # aaa_00100_bbb_0.25000
Of course, it is also possible to embed the value of a variable directly into a string without specifying the format, which is simpler than using the + operator.
s = '<>_<>_<>_<>'.format(s1, i, s2, f) print(s) # aaa_100_bbb_0.25
For more information about format() and str.format() , including format specification strings, see the following article.
In Python 3.6 or later, you can also use f-strings for a more concise syntax.
s = f's1>_i:05>_s2>_f:.5f>' print(s) # aaa_00100_bbb_0.25000 s = f's1>_i>_s2>_f>' print(s) # aaa_100_bbb_0.25
Join a list of strings into one string: join()
You can concatenate a list of strings into a single string with the string method, join() .
Call the join() method from ‘STRING_TO_INSERT’ and pass [LIST_OF_STRINGS] .
'STRING_TO_INSERT'.join([LIST_OF_STRINGS])
Using an empty string » will simply concatenate [LIST_OF_STRINGS] , while using a comma , creates a comma-delimited string. If a newline character \n is used, a newline will be inserted between each string.
l = ['aaa', 'bbb', 'ccc'] s = ''.join(l) print(s) # aaabbbccc s = ','.join(l) print(s) # aaa,bbb,ccc s = '-'.join(l) print(s) # aaa-bbb-ccc s = '\n'.join(l) print(s) # aaa # bbb # ccc
Note that join() can also take other iterable objects, like tuples, as its arguments.
Use split() to split a string separated by a specific delimiter into a list. See the following article for details.
Join a list of numbers into one string: join() , str()
Using join() with a non-string list raises an error.
l = [0, 1, 2] # s = '-'.join(l) # TypeError: sequence item 0: expected str instance, int found
If you want to concatenate a list of numbers, such as int or float , into a single string, convert the numbers to strings using list comprehension with str() . Then, concatenate them using join() .
s = '-'.join([str(n) for n in l]) print(s) # 0-1-2
You can also use a generator expression, which is similar to list comprehensions but creates a generator instead. Generator expressions are enclosed in parentheses () . However, if the generator expression is the only argument of a function or method, you can omit the parentheses.
s = '-'.join((str(n) for n in l)) print(s) # 0-1-2 s = '-'.join(str(n) for n in l) print(s) # 0-1-2
While generator expressions generally use less memory than list comprehensions, this advantage is not significant with join() , which internally converts a generator to a list.
See the following article for details on list comprehensions and generator expressions.