Merge list to string python

Use str.join:

>>> words = ['this', 'is', 'a', 'sentence']
>>> '-'.join(words)
'this-is-a-sentence'
>>> ' '.join(words)
'this is a sentence'

Merge list to string python

Mateen Ulhaq

22.2k16 gold badges86 silver badges127 bronze badges

answered Sep 17, 2012 at 5:33

Burhan KhalidBurhan Khalid

164k18 gold badges238 silver badges276 bronze badges

11

A more generic way to convert Python lists to strings would be:

>>> my_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_lst_str = ''.join(map(str, my_lst))
>>> print(my_lst_str)

answered Dec 1, 2015 at 3:11

Aaron SAaron S

4,5534 gold badges28 silver badges29 bronze badges

4

It's very useful for beginners to know why join is a string method.

It's very strange at the beginning, but very useful after this.

The result of join is always a string, but the object to be joined can be of many types (generators, list, tuples, etc).

.join is faster because it allocates memory only once. Better than classical concatenation (see, extended explanation).

Once you learn it, it's very comfortable and you can do tricks like this to add parentheses.

>>> ",".join("12345").join(("(",")"))
Out:
'(1,2,3,4,5)'

>>> list = ["(",")"]
>>> ",".join("12345").join(list)
Out:
'(1,2,3,4,5)'

heilala

6637 silver badges16 bronze badges

answered May 14, 2016 at 13:55

WallebotWallebot

6875 silver badges7 bronze badges

4

Edit from the future: Please don't use the answer below. This function was removed in Python 3 and Python 2 is dead. Even if you are still using Python 2 you should write Python 3 ready code to make the inevitable upgrade easier.


Although @Burhan Khalid's answer is good, I think it's more understandable like this:

from str import join

sentence = ['this','is','a','sentence']

join(sentence, "-") 

The second argument to join() is optional and defaults to " ".

Anupam

14.2k18 gold badges63 silver badges92 bronze badges

answered Nov 2, 2015 at 1:51

SilentVoidSilentVoid

4925 silver badges10 bronze badges

4

list_abc = ['aaa', 'bbb', 'ccc']

string = ''.join(list_abc)
print(string)
>>> aaabbbccc

string = ','.join(list_abc)
print(string)
>>> aaa,bbb,ccc

string = '-'.join(list_abc)
print(string)
>>> aaa-bbb-ccc

string = '\n'.join(list_abc)
print(string)
>>> aaa
>>> bbb
>>> ccc

answered Sep 3, 2020 at 9:18

Merge list to string python

We can also use Python's reduce function:

from functools import reduce

sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)

the Tin Man

156k41 gold badges209 silver badges297 bronze badges

answered Nov 29, 2018 at 11:15

Merge list to string python

1

We can specify how we join the string. Instead of '-', we can use ' ':

sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)

the Tin Man

156k41 gold badges209 silver badges297 bronze badges

answered Oct 18, 2019 at 7:46

Merge list to string python

If you want to generate a string of strings separated by commas in final result, you can use something like this:

sentence = ['this','is','a','sentence']
sentences_strings = "'" + "','".join(sentence) + "'"
print (sentences_strings) # you will get "'this','is','a','sentence'"

Tomerikoo

16.6k15 gold badges37 silver badges54 bronze badges

answered Jun 30, 2020 at 15:20

Merge list to string python

CarmorenoCarmoreno

1,15815 silver badges26 bronze badges

If you have a mixed content list and want to stringify it, here is one way:

Consider this list:

>>> aa
[None, 10, 'hello']

Convert it to string:

>>> st = ', '.join(map(str, map(lambda x: f'"{x}"' if isinstance(x, str) else x, aa)))
>>> st = '[' + st + ']'
>>> st
'[None, 10, "hello"]'

If required, convert back to the list:

>>> ast.literal_eval(st)
[None, 10, 'hello']

the Tin Man

156k41 gold badges209 silver badges297 bronze badges

answered Jan 27, 2021 at 10:21

1

def eggs(someParameter):
    del spam[3]
    someParameter.insert(3, ' and cats.')


spam = ['apples', 'bananas', 'tofu', 'cats']
eggs(spam)
spam =(','.join(spam))
print(spam)

Paul Roub

36k27 gold badges80 silver badges88 bronze badges

answered May 7, 2020 at 21:18

1

Without .join() method you can use this method:

my_list=["this","is","a","sentence"]

concenated_string=""
for string in range(len(my_list)):
    if string == len(my_list)-1:
        concenated_string+=my_list[string]
    else:
        concenated_string+=f'{my_list[string]}-'
print([concenated_string])
    >>> ['this-is-a-sentence']

So, range based for loop in this example , when the python reach the last word of your list, it should'nt add "-" to your concenated_string. If its not last word of your string always append "-" string to your concenated_string variable.

answered Jul 7, 2020 at 11:03

Merge list to string python

How do I concatenate items in a list to a single string?

Using join() method to concatenate items in a list to a single string. The join() is an inbuilt string function in Python used to join elements of the sequence separated by a string separator. This function joins elements of a sequence and makes it a string.

How do you join words in a list in python?

Note: The join() method provides a flexible way to create strings from iterable objects. It joins each element of an iterable (such as list, string, and tuple) by a string separator (the string on which the join() method is called) and returns the concatenated string.

How do you combine list elements in python?

The most conventional method to concatenate lists in python is by using the concatenation operator(+). The “+” operator can easily join the whole list behind another list and provide you with the new list as the final output as shown in the below example.

What does join () do in python?

The join() method takes all items in an iterable and joins them into one string. A string must be specified as the separator.