Python string stitching

In the actual development of Python, many need to use string splicing, there are a lot of string splicing in Python, sum up today:

Splicing with + symbol

Stitch with % symbol

Stitching with join()

Splicing with the format() method

Use the Template object in the string module

example:

Fruit1 = 'apples'
Fruit2 = 'bananas'
Fruit3 = 'pears'

Claim:
Output string 'There are apples, bananas, pears on the table'

Splicing with + symbol

Use + to splic the string as follows:

str = 'There are' + fruit1 + ',' + fruit2 + ',' + fruit3 + 'on the table'

This method is relatively inefficient and is not recommended.

Stitch with % symbol

The method of splicing with % symbol is as follows:

Str = 'There are %s, %s, %s on the table.' % (fruit1,fruit2,fruit3)

In addition to the tuple method, you can also use the dictionary as follows:

str = 'There are% (fruit1 ) s,% (fruit2) s,% (fruit3) s on the table'% { 'fruit1': fruit1, 'fruit2': fruit2, 'fruit3': fruit3} This method is relatively common Stitching with join()

Join()` method is stitched as follows

temp = [ 'There are', fruit1, ',', fruit2, ',', fruit3, 'on the table'] ''. join (temp)

This method uses sequence operations

Splicing with the format() method

Use the format() method to splicing as follows:

Str = 'There are {}, {}, {} on the table' str .format(fruit1,fruit2,fruit3)

You can also specify the location of the parameter:

Str = 'There are {2}, {1}, {0} on the table' str .format(fruit1,fruit2,fruit3) # fruit1 appears at 0

Similarly, you can also use a dictionary:

Str = 'There are {fruit1}, {fruit2}, {fruit3} on the table' str .format(fruit1=fruit1,fruit2=fruit2,fruit3=fruit3) Using the Template object in the string module

Use the Template object in the string module as follows:

from string import Template str = Template ( 'There are $ {fruit1}, $ {fruit2}, $ {fruit3} on the table') # {} is used herein, no mistake, oh str.subsTItute (fruit1 = Fruit1,fruit2=fruit2,fruit3=fruit3) #If parameters are missing, or if you use the safe_subsTItute() method, it will not str.safe_subsTItute(fruit1=fruit1,fruit2=fruit2) #output'There are apples, bananas, ${fruit3} On the table'

to sum up

There are many ways to splicing. Different methods are used in different occasions. Individuals recommend % and format() methods, which are simple and convenient.

Rotary Joint

Spinner Rotary Joint,Fiber Optic Rotary Joint,Rotary Union,Coaxial Rotary Joint

Dongguan Oubaibo Technology Co., Ltd. , https://www.sliprob.com