2009年2月15日星期日

Python连接字符串

在Python中可以使用简单的加法操作,格式化字符串连接或者join()方法来连接字符串。使用+或+=是比较简单的实现连接方式。

格式化字符串连接是通过定义一个带有格式化代码%s的新字符串来实现,并使用额外的字符串作为参数去填充每个字符串格式化代码。这个可能非常有用,特别当要连接一个复杂格式的字符串时。

连接一个字符串列表的最快方式是使用join(wordList)方法,在列表中的每个字符串将被连接在一起。join方法有一点点的特别因为它本质是迭代字符串列表并执行string+=list[x]操作。这样的结果是字符串将被增加到每个列表元素的前面。如果你想在列表中的词之间增加一个空格这个将变得非常有用,因为你只要简单地定义一个包含一个空格的字符串并实现join方法就可以了:

word1 = "A"
word2 = "few"
word3 = "good"
word4 = "words"
wordList = ["A", "few", "more", "good", "words"]

#simple Join
print "Words:" + word1 + word2 + word3 + word4
print "List: " + ' '.join(wordList)

#Formatted String
sentence = ("First: %s %s %s %s." %
(word1,word2,word3,word4))
print sentence

#Joining a list of words
sentence = "Second:"
for word in wordList:
sentence += " " + word
sentence += "."
print sentence

join_str.py

Words:Afewgoodwords
List: A few more good words
First: A few good words.
Second: A few more good words.

Output from join_str.py code

原文:<<Python Phrasebook: Essential Code and Commands> >Joining Strings

[声明]:限于译者水平,文中难免错漏之处,欢迎各位网友批评指正;

没有评论:

发表评论