字符串格式化
更具体的在这里:https://www.cnblogs.com/wupeiqi/articles/5484747.html
字符串格式化,使用更便捷的形式实现字符串的拼接。
1.1 %输出
1.1.1基本格式化操作
name='yunki'
age=18
text='I am %s, I am 18 years old.' % name
text='I am %s, I am %d years old.' %(name,age)
name='yunki'
age=18
text='I am %(name)s, I am %(age)d years old.' % {'name':name,'age':age}
1.2 百分比表示
一旦字符串格式化中存在百分比的显示,一定要加两个百分号,以实现输出%
name='yunki'
text='%s is 50%%'% name
print(text)
1.2 format(推荐)
name='yunki'
age=18
text='i am {0}, I am 18 years old.'.format(name)
text='i am {0}, I am {1} years old.'.format(name,age)
text='i am {0}, I am {1} years old, real name is {0}.'.format(name,age)
name='yunki'
age=18
text='i am {}, I am 18 years old.'.format(name)
text='i am {}, I am {} years old.'.format(name,age)
text='i am {}, I am {} years old, real name is {}.'.format(name,age,name)
name='yunki'
age=18
text='i am {name}, I am 18 years old.'.format(name=name)
text='i am {name}, I am {age} years old.'.format(name=name,age=age)
text='i am {name}, I am {age} years old, real name is {name}.'.format(name=name,age=age)
name='yunki'
age=18
text='i am {0}, I am {1} years old.'.format(name,age)
data1=text.format(name,age)
data2=text.format('ali',15)
1.3 f ‘{string}’(python 3.6++)
name='yunki'
age=18
text=f'I am {name},I am {age} years old.'
name='yunki'
age=18
text=f'I am {name},I am {age+2} years old.'
name='yunki'
age=18
text=f'I am {name},I am {age+2=} years old.'
age=18
a1=f'I am {age} years old'
a2=f'I am {age:#b} years old'
a3=f'I am {age:#o} years old'
a4=f'I am {age:#x} years old'
name='yunki'
age=18
text=f'I am {'yunki'}.'
name='yunki'
text=f'I am {name}.'
name='yunki'
text=f'I am {name.upper()}.'
参考文献:
https://www.cnblogs.com/wupeiqi/articles/5484747.html
|