在Python中是否有类似于PHP中的implode函数?我已经读取并分割了一组分隔的单词,现在想要以随机顺序排序它们,并用空格将单词打印出来。
implode — 使用字符串连接数组元素
在Python中是否有类似于PHP中的implode函数?我已经读取并分割了一组分隔的单词,现在想要以随机顺序排序它们,并用空格将单词打印出来。
implode — 使用字符串连接数组元素
print(' '.join(['word1', 'word2', 'word3']))
您可以连接任何可迭代对象(不仅限于此处使用的list
),当然您可以使用任何字符串(不仅限于' '
)作为分隔符。
如果你想要像你在问题中提到的随机顺序,使用shuffle。
在评论中有这样一个问题:为什么Python会抛出错误,如果你这样做:"glue".join(["startString", 123, "endString"])
。 join
操作的是字符串的可迭代对象。在 Python 中没有隐式类型转换。
但是这当然有解决办法。只需自己进行转换即可。
"glue".join(map(str, ["startString",123,"endString"]))
好的,我刚刚找到了一个可以做我想做的事情的函数;
我读入的文件是以以下格式存储单词的:
Jack/Jill/my/kill/name/bucket
然后我使用split()
方法将其拆分为列表,一旦我把单词转换成列表后,我用这种方法来连接这些单词:
concatenatedString = ' - '.join(myWordList)
# ie: delimeter.join(list)
<?php declare(strict_types=1);var_dump(implode("glue",["startString",(int)123,"endString"]));
将输出string(31) "startStringglue123glueendString"
但是在Python中,执行"glue".join(["startString",123,"endString"]);
将会出现TypeError: sequence item 1: expected str instance, int found
的错误提示。 - hanshenrik