python - Pourquoi est-ce string.join(liste) au lieu de list.join(string)

Mots clés : pythonstringlistpython

meilleur 3 Réponses python - Pourquoi est-ce string.join(liste) au lieu de list.join(string)

vote vote

98

'_'.join(['welcome', 'to', 'stack', 'overflow']) '_'.join(('welcome', 'to', 'stack', 'overflow')) 
'welcome_to_stack_overflow' 
TypeError: sequence item 0: expected str instance, int found 
vote vote

84

>>> b"".join <built-in method join of bytes object at 0x00A46800> >>> "".join <built-in method join of str object at 0x00A28D40> 
vote vote

71

some_strings = ('foo', 'bar', 'baz') 
class OurList(list):      def join(self, s):         return s.join(self) 
>>> l = OurList(some_strings) # step 1, create our list >>> l.join(', ') # step 2, use our list join method! 'foo, bar, baz' 
>>> ' | '.join(some_strings) # a single step! 'foo | bar | baz' 
>>> import timeit >>> min(timeit.repeat(lambda: ''.join(str(i) for i in range(10) if i))) 3.839168446022086 >>> min(timeit.repeat(lambda: ''.join([str(i) for i in range(10) if i]))) 3.339879313018173 

Questions similaires