解释空delimi的语法

2024-04-19 11:07:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在读一本书,下面是其中提供的一个小代码:

>>>S='shrubbery'
>>>L=list(S)
>>>L
>>>['s', 'h', 'r', 'u', 'b', 'b', 'e', 'r', 'y']
>>>L[1]='c'
>>>''.join(L)
'scrubbery'

有人能解释一下最后一个命令“”的语法吗?join(L) 我知道它在做什么…但有点奇怪。。。在这个命令中哪个是对象或类?“”是字符串对象,join()是方法。。。。在

谢谢


Tags: 对象方法字符串代码命令语法listjoin
2条回答

the docs

str.join(iterable)

Return a string which is the concatenation of the strings in the iterable iterable. The separator between elements is the string (str) providing this method.

因此''.join(L)连接L的元素,用空字符串将它们彼此分隔开来。在

您可能会想知道为什么这个方法看起来如此倒退(例如,为什么不L.join(''))?原因很简单:结果永远是字符串,分隔符永远是字符串。而且,由于该方法应该作用于任何可以提供其成员的字符串表示形式的任何iterable,因此在字符串分隔符上定义它一次是有意义的,而不是为每个可能的iterable定义多次。在

字符串strjoin方法使用str字符串将传递给它的字符串列表连接到单个字符串中,即','.join(['1', '2', '3'])将返回'1,2,3'。在

''是一个空字符串,因此字符串列表将使用空分隔符连接,即''.join(['1', '2', '3'])返回{}。在

相关问题 更多 >