somepeople

python学习第二天-格式化输出

占位符:

  %s

  接收任意数据类型,str、int、float,然后都转化成字符串形式

id = 1.45454646
print('hello %s'%id)
#hello 1.45454646
id = 'sdsd'
print('hello %s'%id)

#hello sdsd

 

  %d 

  要求变量必须为数字,如果是float类型,会转化成整数

id = 199.343
print('hello %d'%id)
#hello 199

  %f

  要求变量必须为数字,如果是int类型,会转化成float类型

id = 3535
print('hello %f'%id)
#hello 3535.000000

  %r

  返回原来变量的赋值信息及格式

formatter = "%r %r %r %r"

print(formatter % (1, 2, 3, 4))
print(formatter % ("one", "two", "three", "four"))
print(formatter % (True, False, False, True))
print(formatter % (formatter, formatter, formatter, formatter))
print(formatter % (
    "I had this thing.",
    "That you could type up right.",
    "But it didn't sing.",
    "So I said goodnight."
))
#1 2 3 4
#'one' 'two' 'three' 'four'
#True False False True
#'%r %r %r %r' '%r %r %r %r' '%r %r %r %r' '%r %r %r %r'
#'I had this thing.' 'That you could type up right.' "But it didn't sing." 'So I said goodnight.'

 format

  

name = 'Ryan'
age = 18
print('my name is {} , Im {} years old'.format(name,age))
print('my name is {0} , Im {1} years old'.format(name,age))
print('my name is {element1} , Im {element2} years old'.format(element1=name,element2=age))
#my name is Ryan , Im 18 years old
#my name is Ryan , Im 18 years old
#my name is Ryan , Im 18 years old

 

posted on 2020-07-05 11:37  Hello_Thanos  阅读(149)  评论(0编辑  收藏  举报

导航