Summarize 3 methods of merging strings in Python

伊谢尔伦
Release: 2017-06-28 13:40:48
Original
2093 people have browsed it

This article mainly introduces 3 methods of Pythonmerging strings. This article explains the use of +=operator, the use of % operator, Use the ' '.join() method of String for 3 methods. Friends who need it can refer to the following

Purpose

Merging strings into one large string, more consideration is given to performance

Method

Common methods include the following:

1. Use the += operator


  BigString=small1+small2+small3+...+smalln
Copy after login


For example, there is a fragment pieces=['Today','is','really' ,'a','good','day'], we want to connect it

BigString=' '
for e in pieces:
        BigString+=e+' '
Copy after login

or use

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

2. Use the % operator

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

3. Use String's ' '.join() method

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

About performance

There are a small number of strings that need to be spliced , try to use the % operator to keep the code readable

There are a large number of strings that need to be spliced, use the ''.join method, which only uses a copy of the pieces without creating an intermediate between the sub-items. result.

The above is the detailed content of Summarize 3 methods of merging strings in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!