How to concatenate (join) items in a list to a single string
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puddle Jumping Looping
--
Chapters
00:00 Question
00:49 Accepted answer (Score 1849)
01:03 Answer 2 (Score 230)
01:20 Answer 3 (Score 58)
02:11 Answer 4 (Score 17)
02:50 Thank you
--
Full question
https://stackoverflow.com/questions/1245...
Question links:
[How do I append one string to another in Python?]: https://stackoverflow.com/questions/4435...
[How do I split a string into a list of characters?]: https://stackoverflow.com/q/4978787
[How do I split a string into a list of words?]: https://stackoverflow.com/questions/7438.../
Accepted answer links:
[str.join]: https://docs.python.org/library/stdtypes...
Answer 3 links:
[why join is a string method]: https://stackoverflow.com/questions/4938...
[extended explanation]: https://paolobernardi.wordpress.com/2012.../
Answer 4 links:
[@Burhan Khalid's answer]: https://stackoverflow.com/a/12453584
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #string #list #concatenation
#avk47
ACCEPTED ANSWER
Score 2029
Use str.join:
>>> words = ['this', 'is', 'a', 'sentence']
>>> '-'.join(words)
'this-is-a-sentence'
>>> ' '.join(words)
'this is a sentence'
ANSWER 2
Score 270
A more generic way (covering also lists of numbers) to convert a list to a string 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
ANSWER 3
Score 68
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)'
ANSWER 4
Score 18
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 " ".