Cheap VPS host selection
Provide server host evaluation information

The latest string splicing method in python 3 (F-string/parentheses/Template template)

The most popular and popular version of python is 3. x. In this version, some new string splicing methods have been added and the original methods have been modified accordingly. What follows is the latest string splicing method in python 3. Let's continue to read the article to learn.

 twenty thousand two hundred and twenty trillion and five hundred and ten billion one hundred and seventy-two million four hundred and fifty-four thousand one hundred and fifty-two

1、 F-string

After python was updated to version 3.6.2, a new string format method, f-string, was introduced. It can modify a string with the lowercase letter f, and then use curly braces in the string to indicate the inserted value. Just write the name of the string object in these curly braces to realize the splicing operation. It is also called string interpolation, because strings can be spliced at any position. The code is as follows:

 s1= 'Hello' s2= 'World' a =  f' {s1} {s2} '
 print (a) HelloWorld

2、 Parenthesis

Parentheses, also known as parentheses, play an important role in any programming language, and the most important role is to include multiple objects. In Python, parentheses are used to write a string code in multiple lines, but when there are multiple string objects in the parentheses, they will be connected by default. The code is as follows:

 s = (      'Hello'      'World' ) print (s) HelloWorld

3、 Template

In Python, the string data type is str, which already contains many methods that can be used for string objects. However, there is also a built-in module called string. You can use the Template object in this module to instantiate a string template. Then call safe_substitute() and specify the string required by the template placeholder to realize the splicing operation. The detailed code example is shown below;

 from  string   import  Template s = Template( '${s1} ${s2}!'  print (s.safe_substitute(s1= 'Hello' ,s2= 'World' ))

This is the introduction of Python 3 string splicing method.

Do not reprint without permission: Cheap VPS evaluation » The latest string splicing method in python 3 (F-string/parentheses/Template template)