Python Format function Foramt

Source: Internet
Author: User

#通过位置
print ' {0},{1} '. Format (' Chuhao ', 20)

print ' {},{} '. Format (' Chuhao ', 20)

print ' {1},{0},{1} '. Format (' Chuhao ', 20)

#通过关键字参数
print ' {name},{age} '. Format (age=18,name= ' Chuhao ')

Class Person:
def __init__ (self,name,age):
Self.name = Name
Self.age = Age

def __str__ (self):
Return ' This guy was {self.name},is {self.age} old '. Format (self=self)

Print str (person (' Chuhao ', 18))

#通过映射 List
A_list = [' Chuhao ', ' China ']
print ' My name ' {0[0]},from {0[2]},age is {0[1]} '. Format (a_list)
#my name is Chuhao,from China,age is 20

#通过映射 Dict
b_dict = {' name ': ' Chuhao ', ' Age ': ' Province ': ' Shanxi '}
print ' My name ' {name}, age ' {age},from {province} '. Format (**b_dict)
#my name is Chuhao, 20,from Shanxi

#填充与对齐
print ' {: >8} '. Format (' 189 ')
# 189
print ' {: 0>8} '. Format (' 189 ')
#00000189
print ' {: a>8} '. Format (' 189 ')
#aaaaa189

#精度与类型f
#保留两位小数
print ' {:. 2f} '. Format (321.33345)
#321.33

#用来做金额的千位分隔符
print ' {:,} '. Format (1234567890)
#1, 234,567,890

#其他类型 is mainly into the system, B, D, O, X is binary, decimal, octal, hexadecimal.

print ' {: b} '. Format #二进制 10010
print ' {:d} '. Format #十进制 18
print ' {: o} '. Format #八进制 22
print ' {: x} '. Format #十六进制12

This article was transferred from https://www.cnblogs.com/gide/p/6955895.html

Python Format function Foramt

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.