formatting strings using the Format function method

Source: Internet
Author: User
Format

First, the grammar

Replace% with {} and:

Ii. examples

Name = "Bigberg" age = 18msg1= "My name was {},and my age is {}.". Format (name,age) msg2= "My name is {0},and my age is {1}.". Format (name,age) msg3= "My name is {_name},and my age is {_age}.". Format (_name=name,_age=age) msg4= "My name is {1},and my age is {0},and My brother's age is {0}.". Format (age,name) print (MSG1) print (MSG2) print (MSG3) print (MSG4) #输出my name is Bigberg,and my age was 18.my name is Bigberg, And my age are 18.my name is Bigberg,and my age is 18.my name is Bigberg,and my age is 18,and my brother's age is 18.

The Format function of the string can accept an unlimited number of parameters, the position can be out of order , can not be used or multiple times , but 2.6 can not be empty {},2.7 later .

Three, subscript gets the element

info = ["Bigberg", 18]msg= ' {0[0]},{0[1]} '. Format (info) print (msg) #输出bigberg, 18

Four, format qualifiers

The syntax is {:}

  1. Fill and align

Fill and use with Chi Chang

^, <, > are centered, left-aligned, right-aligned, followed by width. : The character that is padded later, can only be one character, and does not specify a space padding by default.

Number = 234print (' {: >8} '. Format (number)) print (' {:* >8} '. Format (number)) #输出     234*****234

  2. Accuracy and type F

num = 123.23423print (' {:. 2f} '. Format (num)) #输出123.23

Where. 2 represents a precision of 2 length, and F denotes float type

 3. Binary

B, D, O, and x indicate binary, decimal, octal, and hexadecimal, respectively

num = 25print (' {: b} '. Format (num)) print (' {:d} '. Format (num)) print (' {: o} '. Format (num)) print (' {: x} '. Format (num)) # Output 11001253119
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.