Home  >  Article  >  Backend Development  >  Python合并字符串的3种方法

Python合并字符串的3种方法

WBOY
WBOYOriginal
2016-06-06 11:17:221565browse

目的

  将一些小的字符串合并成一个大字符串,更多考虑的是性能

方法

   常见的方法有以下几种:

1.使用+=操作符

代码如下:


  BigString=small1+small2+small3+...+smalln


例如有一个片段pieces=['Today','is','really','a','good','day'],我们希望把它联起来

代码如下:


BigString=' '
for e in pieces:
        BigString+=e+' '


或者用

代码如下:


import operator
BigString=reduce(operator.add,pieces,' ')

2.使用%操作符

代码如下:


In [33]: print '%s,Your current money is %.1f'%('Nupta',500.52)
Nupta,Your current money is 500.5

3.使用String的' '.join()方法

代码如下:


In [34]: ' '.join(pieces)
Out[34]: 'Today is really a good day'

关于性能

有少量字符串需要拼接,尽量使用%操作符保持代码的可读性

有大量字符串需要拼接,使用''.join方法,它只使用了一个pieces的拷贝,而无须产生子项之间的中间结果。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn