gpt4 book ai didi

python - 为什么是 string.join(list) 而不是 list.join(string)?

转载 作者:bug小助手 更新时间:2023-10-28 01:28:00 26 4
gpt4 key购买 nike

这一直让我感到困惑。看起来这样会更好:

["Hello", "world"].join("-")

比这个:

"-".join(["Hello", "world"])

这样有什么特殊原因吗?

最佳答案

这是因为任何iterable都可以被join(例如,list、tuple、dict、set),但它的内容和“joiner”必须是字符串。

例如:

'_'.join(['welcome', 'to', 'stack', 'overflow'])
'_'.join(('welcome', 'to', 'stack', 'overflow'))
'welcome_to_stack_overflow'

使用字符串以外的东西会引发以下错误:

TypeError: sequence item 0: expected str instance, int found

关于python - 为什么是 string.join(list) 而不是 list.join(string)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/493819/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com