136

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

http://php.net/manual/en/function.implode.php

JS.
16.5k13 gold badges67 silver badges79 bronze badges
asked Aug 21, 2012 at 10:46
0

2 Answers 2

229

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"]))

answered Aug 21, 2012 at 10:48
Sign up to request clarification or add additional context in comments.

2 Comments

join() works great if you have an array of strings, but if any member of the array is int instead of a string, you'll get a TypeError, php's implode doesn't do that, even in strict mode =/ <?php declare(strict_types=1);var_dump(implode("glue",["startString",(int)123,"endString"])); gives you string(31) "startStringglue123glueendString" but in python doing "glue".join(["startString",123,"endString"]); gives you TypeError: sequence item 1: expected str instance, int found
@hanshenrik fix is "_".join(map(str, tuple)) or trough comprehension "_".join([str(x) for x in tuple])
15

Okay I've just found a function that does what I wanted to do;

I read in a file with words in a format like: Jack/Jill/my/kill/name/bucket

I then split it up using the split() method and once I had the word into an list, I concatenated the words with this method:

concatenatedString = ' - '.join(myWordList)
# ie: delimeter.join(list)
answered Aug 21, 2012 at 10:54

1 Comment

I don't get why you want to join. First you have a line, you split it into characters and then join it again. Why don't you replace the characters in the first place? (You miss the 'random' part in your own answer, not relevant anymore?)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.