Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there a simpler way to concatenate string items in a list into a single string? Can I use the str.join() function?

E.g. this is the input ['this','is','a','sentence'] and this is the desired output this-is-a-sentence

sentence = ['this','is','a','sentence'] sent_str = "" for i in sentence:     sent_str += str(i) + "-" sent_str = sent_str[:-1] print sent_str 
like image 509
alvas Avatar asked Sep 17 '12 05:09

alvas


People also ask

How do I join a list of elements into a string?

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 concatenate items in a list?

The most conventional method to perform the list concatenation, the use of “+” operator can easily add the whole of one list behind the other list and hence perform the concatenation.

How do I convert a list to a string in one line?

To convert a list to a string in one line, use either of the three methods: Use the ''. join(list) method to glue together all list elements to a single string. Use the list comprehension method [str(x) for x in lst] to convert all list elements to type string.

How do you join a list into a string in python?

The most pythonic way of converting a list to string is by using the join() method. The join() method is used to facilitate this exact purpose. It takes in iterables, joins them, and returns them as a string. However, the values in the iterable should be of string data type.


2 Answers

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) '12345678910' 
like image 38
Aaron S Avatar answered Oct 06 '22 13:10

Aaron S


Use str.join:

>>> sentence = ['this', 'is', 'a', 'sentence'] >>> '-'.join(sentence) 'this-is-a-sentence' >>> ' '.join(sentence) 'this is a sentence' 
like image 96
Burhan Khalid Avatar answered Oct 06 '22 14:10

Burhan Khalid