string.join如何解决?我尝试使用它如下:
import string
list_of_str = ['a','b','c']
string.join(list_of_str.append('d'))
Run Code Online (Sandbox Code Playgroud)
但是得到了这个错误(在2.7.2中完全相同的错误):
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/string.py", line 318, in join
return sep.join(words)
TypeError
Run Code Online (Sandbox Code Playgroud)
如果您尝试再次加入list_of_string,则可以看到附加确实发生了:
print string.join(list_of_string)
-->'a b c d'
Run Code Online (Sandbox Code Playgroud)
这是来自string.py的代码(找不到sep内置str.join()的代码):
def join(words, sep = ' '):
"""join(list [,sep]) -> string
Return a string composed of the words in list, with
intervening occurrences of sep. The default separator is a
single space.
(joinfields and join are synonymous)
"""
return sep.join(words)
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?这是一个错误吗?如果它是预期的行为,它如何解决/为什么会发生?我觉得我要么学习一些关于python执行其函数/方法的顺序的有趣内容,或者我只是遇到了Python的历史怪癖.
旁注:当然,它只是事先做了追加:
list_of_string.append('d')
print string.join(list_of_string)
-->'a b c d'
Run Code Online (Sandbox Code Playgroud)
list_of_str.append('d')
Run Code Online (Sandbox Code Playgroud)
没有返回新的list_of_str.
该方法append没有返回值,因此返回None.
为了使它工作,你可以这样做:
>>> import string
>>> list_of_str = ['a','b','c']
>>> string.join(list_of_str + ['d'])
Run Code Online (Sandbox Code Playgroud)
虽然这不是很Pythonic,但没有必要import string......这种方式更好:
>>> list_of_str = ['a','b','c']
>>> ''.join(list_of_str + ['d'])
Run Code Online (Sandbox Code Playgroud)