为什么在Python中使用string.join(list)而不是list.join(string)?

join() is a string method and while using it the separator string iterates over an arbitrary sequence, forming string representations of each of the elements, inserting itself between the elements.

join()是一个字符串方法,使用它时,分隔符字符串会在任意序列上迭代,从而形成每个元素的字符串表示形式,并在元素之间插入自己。

Concisely, it's because join and string.join() are both generic operations that work on any iterable and is a string method.

简而言之,这是因为join和string.join()都是可在任何可迭代对象上使用的通用操作,并且是字符串方法。

Because it is a string method, the join() can work for the Unicode string as well as plain ASCII strings.

因为它是一个字符串方法,所以join()可以用于Unicode字符串以及普通ASCII字符串。

Example Usage of string.join(list)

示例string.join(list)的用法

-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> test_string = "test"
>>> test_string.join("1234")
'1test2test3test4'
>>>

In the above example, the string "test" is joined with every character provided as a join argument.

在上面的示例中,字符串“ test”与作为连接参数提供的每个字符连接在一起。

-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> test_string = "test"
>>> test_string.join("---")
'-test-test-'
>>>


翻译自: https://www.includehelp.com/python/why-is-it-string-join-list-instead-of-list-join-string.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值