The format function is used to format strings.

Source: Internet
Author: User

The format function is used to format strings.

Format

 

I. Syntax

Replace % by {} and:

Ii. Examples

Name = "bigberg" age = 18msg1 = "my name is {}, 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) # output my name is bigberg, and my age is 18.my name is bigberg, and my age is 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 a string can accept unlimited parameters and the position is acceptable.Not in order.Multiple times, But 2.6 cannot be blank {}. It will be available after 2.7.

 

Iii. subscripts to obtain elements

Info = ["bigberg", 18] msg = '{0 [0]}, {0 [1]}'. format (info) print (msg) # output bigberg, 18

 

Iv. Format qualifier

Syntax {:}

  1. Fill and align

Fill and alignment are often used together

^, <,> Are center, left, right, and back with width. : Enter only one character. If this parameter is not specified, it is filled with spaces by default.

Number = 234 print ('{:> 8 }'. format (number) print ('{: *> 8 }'. format (number) # output 234 ***** 234

  

  2. Precision and Type f

Num = 123.23423 print ('{:. 2f}'. format (num) # output 123.23

Where. 2 indicates the precision of the length of 2, and f indicates the float type.

  

 3. hexadecimal

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

Num = 25 print ('{: B }'. format (num) print ('{: d }'. format (num) print ('{: o }'. format (num) print ('{: x }'. format (num) # output 11001253119

  

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.