printf:% concatenation string and format function in Python

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.