In C, we use the form of printf ("%s", "Hello") for string concatenation
In Python, there are two implementations of such stitching, the percent concatenation, and the use of the Format function, which shows the following code
% Number Stitching string
In Python it is possible to stitch strings with the% number, which is irrelevant to the print function. Here are some examples
- Print a string
" I am%s,my blogs is%s " % ("codescrew","www.cnblogs.com/codescrew") Print(msg)
- Print floating-point numbers
" I am%0.2f m " %1.785print (msg) # printing results for I am 1.78 m
The. 2, which is followed by the% number, indicates that 2 decimal places are reserved
- Print percentage
" It is%0.2f percent " % 99.852print (msg) # Print results for it is 99.85%
- Splicing with key-value pairs
" I am% (name) s.my age was% (age) d" % ({"name":"codescrew ","Age": +})print(msg) # Printing results for I am codescrew.my
The Format function handles strings
In addition to the% number for stitching, you can also use the Format function of the string class, which lists common uses.
msg ="I am {},age is {}". Format ("Codescrew", 23)Print(msg)#printing results For I am Codescrew,age ismsg="I am {1},age is {0}". Format ("Codescrew", 23)Print(msg)#printing results For I am 23,age is codescrewmsg="I am {name},age are {age}". Format (name="Codescrew", age=23)Print(msg)#printing results For I am Codescrew,age ismsg="I am {name},age are {age}". Format (**{"name":"Codescrew"," Age": 23})Print(msg)#printing results For I am Codescrew,age ismsg="I am {: S},age is {:d}". Format ("Codescrew", 23)Print(msg)#printing results For I am Codescrew,age ismsg="I am {: S},age is {:d}". Format (*["Codescrew", 23])Print(msg)#printing results For I am Codescrew,age ismsg="numbers:{:b},{:o},{:d},{:x},{:x}". Format (15,15,15,15,15)Print(msg)#print result is numbers:1111,17,15,f,f
printf:% concatenation string and format function in Python