Is there a simpler way to concatenate string items in list into a single string?
Can I use the str.join()
function to join items in list?
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
Although @Burhan Khalid's answer is good, I think it's more understandable like this:
The second argument to join() is optional and defaults to " ".
EDIT: This function was removed in Python 3
We can also use the python inbuilt functionality of reduce:-
I hope this helps :)
Use
join
:A more generic way to convert python lists to strings would be:
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. extended explanationOnce you learn it, it's very comfortable and you can do tricks like this to add parentheses.