Python——%字符串拼接

字符串格式化

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

1.百分号方式

①不常见的格式化方式

msg='I am my hobby is swimming''Alice'
print(msg)
#I am my hobby is swimmingAlice

msg='I am'+ ' '+',Alice'+' my hobby is swimming'
print(msg)
#I am Alice my hobby is swimming

msg='I am my hobby is swimming','Alice'
print(msg)
#('I am my hobby is swimming', 'Alice')

print('I am my hobby is swimming','Alice')
#I am my hobby is swimming Alice

print('root','x','0','0',sep=':')
#root:x:0:0
print('root'+':'+'x'+':'+'0','0')
#root:x:0 0

②常见的格式化方式 —— %s,%d,%f

msg='I am %s' % 'Alice'
print(msg)
#I am Alice

msg='I am %s ,my hobby is %s' % ('Alice','swimming')
print(msg)
#I am Alice ,my hobby is swimming

name='Alice'
age=21
msg='I am %s ,my age is %d' % (name,age)
print(msg)
#I am Alice ,my age is 21

msg = "I am %(name)s, age %(age)d" % {"name": "Alice", "age": 21}
print(msg)
# I am Alice, age 21


tpl = "percent %.2f" % 99.976234444444444444
print(tpl)
# percent 99.98  保留两位,并四舍五入

#打印百分比
tpl = "percent %.2f %%" % 99.976234444444444444
print(tpl)
# percent 99.98 %

:%s可以表示所有类型的变量,而%d只能表示整形

msg='I am %s ,my age is %d' % ('Alice',21)
print(msg)
#I am Alice ,my hobby is 21

msg='I am %s ,my age is %s' % ('Alice',[1,2,3])
print(msg)
#I am Alice ,my age is [1, 2, 3]

2.format方式

#必须是一一对应,否则就会报错
tpl = "I am {}, age {},sex{}".format("Alice", 18,'女')
print(tpl)
#I am Alice, age 18,女

tpl = "I am {1}, age {0},sex {2}".format(18,"Alice",'女')
print(tpl)
#I am Alice, age 18,sex 女

tpl = "I am {name}, age {age},really {name}".format(name="Alice", age=18)
print(tpl)
#I am Alice, age 18,really Alice

#字典按照键来取
tpl = "I am {name}, age {age}, really {name}".format(**{"name": "Alice", "age": 18})
print(tpl)
#I am Alice, age 18, really Alice

tpl = "I am {:s}, age {:d}".format(*["Alice", 18])
print(tpl)
#I am Alice, age 18

tpl = "I am {:s}, age {:d}".format("Alice", 18)
print(tpl)
#I am Alice, age 18

另补充:

tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%},{}".format(10, 10, 10, 10, 10, 15.87623, 2)
print(tpl)
#{:b}二进制,{:o}八进制,{:d}十进制,{:x}十六进制小写,{:X}十六进制大写, {:%}
#numbers: 1010,12,10,a,A, 1587.623000%,2
发布了27 篇原创文章 · 获赞 7 · 访问量 2123

猜你喜欢

转载自blog.csdn.net/lucky_shi/article/details/104821672