1

string.join 如何解决?我尝试如下使用它:

import string 
list_of_str = ['a','b','c'] 
string.join(list_of_str.append('d'))

但是却得到了这个错误(与 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

追加确实发生了,你可以看到如果你再次尝试加入 list_of_string :

print string.join(list_of_string)
-->'a b c d'

这是来自 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)

这里发生了什么?这是一个错误吗?如果这是预期的行为,它如何解决/为什么会发生?我觉得我要么即将学习一些有趣的关于 python 执行其函数/方法的顺序的东西,要么我刚刚遇到了 Python 的一个历史怪癖。


旁注:当然,预先进行附加是有效的:

list_of_string.append('d')
print string.join(list_of_string)
-->'a b c d'
4

1 回答 1

5
list_of_str.append('d')

不返回新的list_of_str

该方法append没有返回值,因此返回None

为了使它工作,你可以这样做:

>>> import string
>>> list_of_str = ['a','b','c']
>>> string.join(list_of_str + ['d'])

虽然这不是很 Pythonic,也没有必要import string......这种方式更好:

>>> list_of_str = ['a','b','c']
>>> ''.join(list_of_str + ['d'])
于 2012-04-06T05:37:16.707 回答