码迷,mamicode.com
首页 > 编程语言 > 详细

python字符串拼接

时间:2019-08-22 19:11:25      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:学习   print   family   back   tps   10个   color   浮点   颜色   

 Python的字符串格式化有两种方式: 百分号方式、format方式

一、format方式

test = ‘my name is {},age {}‘
v = test.format(‘alex‘, 19)
print(v)
# 输出:my name is alex,age 19
test = ‘names is {1},emil{0}‘
v = test.format(‘101@qq.com‘,‘alex‘)
print(v)
# 输出:names is alice,emil101@qq.com
test = ‘names is {name1},emil{emil1}‘
v = test.format(name1=‘alice‘,emil1=‘101@qq.com‘)
print(v)
# 输出:names is alice,emil101@qq.com
#传入列表
test = ‘names are {},emil{}‘
v = test.format(*([‘alice‘,‘lili‘],[‘101@qq.com‘,‘www@ww.com‘]))
print(v)
# 输出:names are [‘alice‘, ‘lili‘],emil[‘101@qq.com‘, ‘www@ww.com‘]
#传入字典
test = ‘names is {name1},emil{emil1}‘
v = test.format(**{‘name1‘:‘alice‘,‘emil1‘:‘101@qq.com‘})
print(v)
# 输出:names is alice,emil101@qq.com

 

二、百分号方式

#%s:可加任意类型的值 %d:加整数
print(‘i am %s my hobby is %s‘ % (‘alice‘,‘Fitness‘))
#输出结果:i am alice my hobby is Fitness
print(‘i am %s my age is %d‘ % (‘alice‘,19))
#输出结果:i am alice my age is 19

#打印浮点数%f
print(‘percent %.2f‘%99.333333) #保留小数点后2位
# 输出结果:percent 99.33
print(‘percent %f‘%99.12345689) #默认保留小数点后6位
# 输出结果:percent 99.123457

#打印百分号
print(‘percent %.2f%%‘%99.333333) #保留小数点后两位
# 输出结果:percent 99.33%

#字典
print("i am %(name)s age %(age)d" % {"name": "alex", "age": 18})
# 输出结果:i am alex age 18

#打印加空格
print(‘i am %+10s my age is %d‘ % (‘alice‘,19)) #左边加10个空格
# 输出结果:i am      alice my age is 19
print(‘i am %-10s my age is %d‘ % (‘alice‘,19)) #右边加10个空格
# 输出结果:i am alice      my age is 19

#打印加颜色:\033[88;1m    \033[0m
print(‘i am \033[45;1m%-10s\033[0m my age is %d‘ % (‘alice‘,19))
#输出结果:
技术图片

 

 

 

 

 

 

 

 

 

学习材料来源:

https://www.cnblogs.com/wupeiqi/articles/5484747.html

python字符串拼接

标签:学习   print   family   back   tps   10个   color   浮点   颜色   

原文地址:https://www.cnblogs.com/lijinping716/p/11379692.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!