Format and pythonformat

Source: Internet
Author: User

Format and pythonformat

Usage:

It uses {} And: to replace the traditional % method.

 

1. Use location parameters

Key point: The following example shows that the location parameter is not subject to the order and can be {}. As long as there is a corresponding parameter value in the format, the parameter index is enabled from 0, input location parameter list available * List

>>> li = ['hoho',18]>>> 'my name is {} ,age {}'.format('hoho',18)'my name is hoho ,age 18'>>> 'my name is {1} ,age {0}'.format(10,'hoho')'my name is hoho ,age 10'>>> 'my name is {1} ,age {0} {1}'.format(10,'hoho')'my name is hoho ,age 10 hoho'>>> 'my name is {} ,age {}'.format(*li)'my name is hoho ,age 18'

 

2. Use keyword Parameters

Key point: the keyword parameter value must be correct. You can use a dictionary. When the keyword parameter is passed in, add ** before the dictionary.

>>> hash = {'name':'hoho','age':18}>>> 'my name is {name},age is {age}'.format(name='hoho',age=19)'my name is hoho,age is 19'>>> 'my name is {name},age is {age}'.format(**hash)'my name is hoho,age is 18'

 

3. Filling and formatting

: [Fill character] [Alignment mode <^>] [width]

>>> '{0: *> 10 }'. format (10) # right alignment '********* 10'> '{0: * <10 }'. format (10) # align left '10 ********* '>' {0: * ^ 10 }'. format (10) # center alignment '***** 10 ****'

 

4. Precision and hexadecimal

>>> '{0 :. 2f }'. format (1/3) '0. 33 '>>>' {0: B }'. format (10) # binary '000000' >>> '{0: o }'. format (10) # '12' >>> '{0: x }'. format (10) # hexadecimal 'A' >>> '{:,}'. format (12369132698) # format '123' in kilobytes'

 

5. Use Indexes

>>> li['hoho', 18]>>> 'name is {0[0]} age is {0[1]}'.format(li)'name is hoho age is 18

 

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.