Table of Contents Hide
join() function which could be used to convert list to string. If the items of the list are not string then you may need to convert them to string datatype first.
Consider this example –
>>> superHero = ['Flash', 'Thor', 'Hulk'] >>> print(''.join(superHero)) FlashThorHulk
Here we have declared a list of superhero. It contains 3 items – Flash, Thor, and Hulk. In the next line we are joining the list with the help of
join() function. The delimiter used for joining the items is an empty string. That’s why all the 3 items will be joined without space – FlashThorHulk.
Joining with delimiter
If you want to add a delimiter between each item of the list, then use this code –
>>> superHero = ['Flash', 'Thor', 'Hulk'] >>> print('-'.join(superHero)) Flash-Thor-Hulk
Here we have use
- as delimiter and so the output become – Flash-Thor-Hulk.
Joining integer items
If the items inside the list are not strings then we will need to typecast them to string first. Look at this code –
>>> avengerMovies = [2012, 2015, 2019, 2020] >>> print('|'.join(str(e) for e in avengerMovies)) 2012|2015|2019|2020
You can also use
map() function to typecast list items to string. Code –
>>> avengerMovies = [2012, 2015, 2019, 2020] >>> print('|'.join(map(str, avengerMovies))) 2012|2015|2019|2020
Using lambda function
Python provides lambda function which can we used to do computations over each item in the list. We can use this lambda function for joining list items to convert to string. Code –
>>> from functools import reduce >>> superHero = ['Flash', 'Thor', 'Hulk'] >>> print(str(reduce(lambda x,y: x+"-"+y, superHero))) Flash-Thor-Hulk
If you are not the fan of builtin functions and wants to do this with loops, then here is the code –
>>> superHero = ['Flash', 'Thor', 'Hulk'] >>> comb = '' >>> for i in superHero: >>> comb += i >>> print(comb) FlashThorHulk
Although this approach is bad in performance in comparison to
Demo might not work in private window (incognito)