2007-06-14

 

Python Cook 1.6 拼接字符串

需求:

要将一些字符串拼接成一个字符串.

讨论:

最容易想到的方法是使用'+':

newstring = str1 + ' ' + str2 + ' ' + str3 + '!'

然而在Python中,不推荐使用上面的做法,这可能造成代码的效率底下.
string对象是不可改变的字符序列,一个'+'操作,要先构造一个新的string对象,然后再做字符串的拼接,而不是直接改变原有的字符串.当一个操作完成后,临时使用的对象又被释放掉了.也就是说,如果有N字符串要拼在一起,使用'+'操作的话,就要生成N-1次临时string对象,做N-1次拼接运算,然后再释放这N-1个临时对象.这样的效率是可想而知的 .
根据上面的说明,推荐使用Python的内建方法:join.

newstring = ' '.join([str1,str2,str3,'!'])

类似的,可以使用另外一种方法来实现我们的需求.
在Python中,可以使用字符串格式化符号:%.像C的printf一样的使用方法:

newstring =  '%s %s %s!' %(str1,str2,str3)

这个方法不但适用字符串的拼接,也适合与多种类型构成字符串,如:

newstring = '%d + %d = %d %s' %(1,2,3,'done')

两种方法各有各的优点:join适用于要拼接的字符串个数不定,且连接字符确定的情况;而%适用于

相关说明:

join(...)

    S.join(sequence) -> string
    
    Return a string which is the concatenation of the strings in the
    sequence.  The separator between elements is S.

标签:


Comments: 发表评论



<< Home

This page is powered by Blogger. Isn't yours?