Python equivalent for PHP's implode?

末鹿安然 提交于 2019-12-03 04:41:10

问题


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


回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/12053236/python-equivalent-for-phps-implode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!