class=”markdown_views prism-atom-one-light”>
Python splicing strings generally have the following methods:
1. Splicing directly through the (+) operator
s = 'Hello'+' '+'World'+'!'
print(s)
Output result: Hello World!
The operation of string concatenation in this way is inefficient, because a new string will be generated when using + to splice two strings in python, and the memory needs to be re-applied to generate a new string. When splicing strings More will naturally affect the efficiency.
2. Splicing by str.join() method
strlist=['Hello',' ' ,'World','!']
print(''.join(strlist ))
Output result: Hello World!
This method is generally used to convert a collection into a string. “.join()” can be a null character or any other character. When it is any other character, the string in the collection will be the character separated, for example:
strlist=['Hello',' ' ,'World','!']
print(','.join( strlist))
Output result: Hello, ,World,!
3. Splicing by str.format() method
s='{} {}!' .format('Hello',' World')
print(s)
Output result: Hello World!
When splicing strings in this way, it should be noted that the number of {} in the string must be consistent with the number of format method parameters, otherwise an error will be reported.
4. Splicing by (%) operator
s = '%s %s!' % ('Hello', 'World')
print(s)
Output result: Hello World!
This method is basically the same as str.format().
5. Multi-line splicing by ()
s = (
'Hello'
' '
'World'
'!'
)
print(s)
Output result: Hello World!
Python will automatically splice multiple lines into one line when encountering unclosed parentheses.
6. Stitching through the Template object in the string module
from string import Template
s = Template('${s1} ${s2}!')
print(s.safe_substitute(s1=’Hello’,s2=’World’))
Output result: Hello World!
Template is implemented by first initializing a string through Template. These strings contain a key. By calling substitute or safe_substitute, the key value corresponds to the parameters passed in the method, so as to import the string at the specified position. The advantage of this method is that you don’t need to worry about parameter inconsistencies causing exceptions, such as:
from string import Template
s = Template('${s1} ${s2} ${s3}!')
print(s.safe_substitute(s1='Hello',s2='World'))
Output result: Hello World ${s3}!
7. Splicing by F-strings
In the python3.6.2 version, PEP 498 proposes a new string formatting mechanism, called “string interpolation” or more commonly known as F-strings, F-strings provide a clear And a convenient way to embed python expressions into strings for formatting:
s1='Hello'
s2='World'
print(f'{s1} {s2}!')
Output result: Hello World!
We can also execute functions in F-strings:
def power(x):
return x*x
x=4
print(f'{x} * {x} = {power(x)}')
Output result: 4 * 4 = 16
And F-strings are fast, much faster than %-string and str.format(), both formatting methods.