Python format function, python string format

Source: Internet
Author: User
Tags python string format

Python format function, python string format

1. The format can accept infinite parameters, and the positions can be unordered:

In [1]: "{}{}". format ("hello", "world") # do not set the location, In the default order Out [1]: 'Hello World' In [2]: "{0} {1 }". format ("hello", "world") # specify the location Out [2]: 'Hello World' In [3]: "{1} {0} {1 }". format ("hello", "world") # specify the location and reuse the parameter Out [3]: 'World hello World' In [4]: "{name} {age }". format (name = "Linda", age = 15) # Use the keyword Out [4]: 'linda 15' # Set the parameter In [5] through the dictionary: info = {"name": "Linda", "age": 15} In [6]: "{name} {age }". format (** info) Out [6]: 'linda 15' # Set the parameter In [7]: my_list = ['hello' through the list ', 'World'] In [8]: "{0 [0]} {0 [1]}". format (my_list) Out [8]: 'Hello world'

2. format control: the syntax is {} with a colon (:)

^, <,> Indicates the center, left, and right alignment, respectively, with width and padding after the sign. Only one character can be entered. If this parameter is not specified, spaces are used by default.

+ Indicates that + is displayed before a positive number, and-is displayed before a negative number. (Space) indicates that a space is added before a positive number.

B, d, o, and x are binary, decimal, octal, and hexadecimal respectively.

# Center display. The length is 4In [9]: "{: ^ 4 }". format ("he") Out [9]: 'hes' # Left alignment, Length: 4, blank space filled with "x" In [10]: "{: x <4 }". format ("he") Out [10]: 'hexx' # displays the positive and negative signs In [11]: "{:+ }". format (-3) Out [11]: '-3' # the binary value of 8 is displayed In [12]: "{: B }". format (8) Out [12]: '000000' # use braces {} to escape braces In [13]: "{} is {0 }}". format ("hello") Out [13]: 'Hello is {0 }'

 

Related Article

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.