string模块的join方法,因此它需要两个参数,一个是list,另一个是分隔符。而且调用时正如cnxo所示,如果你导入了 string模块:
import string
你需要使用string.join()这样来用。
但现在string对象本身就有这样方法,这样它只需要一个分隔符参数。用法为:
'+'.join(list1)
最简单的我们用到了join函数,实例
print ''.join(list('hello'))
把数据连接
word1 = "A"
word2 = "few"
word3 = "good"
word4 = "words"
wordList = ["A", "few", "more", "good", "words"]
print "Words:" + word1 + word2 + word3 + word4
print "List: " + ' '.join(wordList)
实例
word1 = "A"
word2 = "few"
word3 = "good"
word4 = "words"
wordList = ["A", "few", "more", "good", "words"]
#Joining a list of words
sentence = "Second:"
for word in wordList:
sentence += " " + word
sentence += "."
print sentence
综合上面所述看个实例
# splitting strings
string1 = "A, B, C, D, E, F"
print "String is:", string1
print "Split string by spaces:", string1.split()
print "Split string by commas:", string1.split( "," )
print "Split string by commas, max 2:", string1.split( ",", 2 )
print
# joining strings
list1 = [ "A", "B", "C", "D", "E", "F" ]
string2 = "___"
print "List is:", list1
print 'Joining with "%s": %s'
% ( string2, string2.join ( list1 ) )
print 'Joining with "-.-":', "-.-".join( list1 )
转自:http://www.111cn.net/phper/python/38836.htm
来自 http://blog.csdn.net/hmsiwtv/article/details/20398285