Python开发【字符串格式化篇】

1.百分号

__author__ = "Tang"

# + 号 拼接
msg = "i am " + " tang"
print(msg) # i am  tang
# 这个方法少用


# %s 标识符 万能的 %.ns 截取
msg = "my name is %s" % 'tang'
print(msg) # my name is tang

msg = "my name is %.3s" % 'tang'
print(msg) # my name is tan

msg = "my name is %s,age is %s" % ('tang',22)
print(msg) # my name is tang,age is 22

msg = "my name is %s,age is %.4s" % ('tang',22.3345)
print(msg) # my name is tang,age is 22.3

msg = "my name is %s,age is %s" % ('tang',[22,33])
print(msg) # my name is tang,age is 22



# %d 标识符 只能接受整型数字
msg = "my name is %s,age is %d" % ('tang',22)
print(msg) # my name is tang,age is 22


# %f 标识符 接受浮点数 可指定小数位 四舍五入
msg = "age is %f" % 22
print(msg) # ge is 22.000000

msg = "age is %.2f" % 22.356
print(msg) # age is 22.36

# 打印百分比 %%
msg = "percent %.2f %%" % 90.769
print(msg) # percent 90.77 %

# %(key)
msg = "i am %(name)s, age %(age)d"%{"name":"tang","age":18}
print(msg) # i am tang, age 18

# %-ns 左对齐
msg = "i am %-6s my hobby is %s"%("tang","girl")
print(msg) # i am tang   my hobby is girl

# %ns 右对齐
msg = "i am %6s my hobby is %s"%("tang","girl")
print(msg) # i am   tang my hobby is girl

# 以\033[xx;1m 开头    \033[0m 结尾 加颜色  xx 控制颜色
msg = "my name is \033[45;1mtanglaoer\033[0m"
print(msg) # my name is tanglaoer
# print 分隔符 :
print('root','lao','er',sep=':') # root:lao:er

 format

__author__ = "Tang"

# {}
msg = "i am {},age is {}".format("tang",22)
print(msg) # i am tang,age is 22

# {n}
msg = "i am {1},age is {0}".format(22,"tang")
print(msg) # i am tang,age is 22

    # 不一一对应
msg = "i am {1},age is {1}".format(22,"tang")
print(msg) # i am tang,age is tang

# 键值对
msg = "i am {name},age is {age}".format(age = 22,name="tang")
print(msg) # i am tang,age is 22

# 字典
msg = "i am {name},age is {age}".format(**{"name":"tang","age":22})
print(msg) # i am tang,age is 22

# 列表取值
msg = "i am {0[0]},age is {1[0]}".format(["tang","lao","er"],[10,20,30])
print(msg) # i am tang,age is 10

# :x  标识符
msg = "i am {:s},age is {:d}".format("tang",22)
print(msg) # i am tang,age is 22

# 键:标识符
msg = "i am {name:s},age is {age:d}".format(name="tang",age=22)
print(msg) # i am tang,age is 22

"""
:b 二进制
:d 十进制
:o 八进制
:x 十六进制 小写的
:X 十六进制 大写的
:%  百分比 默认6位小数
"""

msg = "numbers:{:b},{:o},{:d},{:x},{:X},{:%}".format(15,15,15,15,15,15)
print(msg) # numbers:1111,17,15,f,F,1500.000000%

 

posted @ 2018-08-14 20:34  Tanglaoer  阅读(255)  评论(0编辑  收藏  举报