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
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.
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.
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.
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.
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'
Use str.join
:
>>> sentence = ['this', 'is', 'a', 'sentence'] >>> '-'.join(sentence) 'this-is-a-sentence' >>> ' '.join(sentence) 'this is a sentence'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With