Question
Asked By – pythonian29033
Is there an equivalent for PHP’s implode in Python? I’ve read in and split up a set of delimited words, and now I want to sort them out in random orders and print the words out with spaces in between.
implode — Join array elements with a string
Now we will see solution for issue: Python equivalent for PHP’s implode?
Answer
Use the strings join-method.
print(' '.join(['word1', 'word2', 'word3']))
You can join any iterable (not only the list
used here) and of course you can use any string (not only ' '
) as the delimiter.
If you want a random order like you said in your question use shuffle.
In the comment there was the question why Python throws an error if you do "glue".join(["startString", 123, "endString"])
. join
operates on an iterable of strings. There is no implicit type conversion in Python.
But of course there is a solution. Just do the conversion yourself.
"glue".join(map(str, ["startString",123,"endString"]))
This question is answered By – Matthias
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0