python-字符串格式化(format)

字符串格式化主要是为了让展示的内容更标准更好看学。

主要分三种情况

1. 基本的语法格式 <模板字符串>.format(模板的内容)

print('微博账号{}请大家关注'.format('小韩在BJ'))    
微博账号小韩在BJ请大家关注
2.包含序号的格式化     序号参数对应后面模板的内容,按位置填充
print('微博账号{}请大家关注,{}'.format('小韩在BJ','很感谢大家'))
微博账号小韩在BJ请大家关注,很感谢大家
print('微博账号{0}请大家关注,{1}'.format('小韩在BJ','很感谢大家'))
微博账号小韩在BJ请大家关注,很感谢大家

print('微博账号{1}请大家关注,{0}'.format('小韩在BJ','很感谢大家'))
微博账号很感谢大家请大家关注,小韩在BJ

3.格式控制 左对齐(<) 右对齐(>) 居中(^) 字符串长度(n) 保留小数点后几位(.nf) 字符串截断(.n)

# 使用方式{:格式化控制符}

# 左对齐
content='谢谢大家关注我的微博账号:小韩在BJ'
print('{:*<20}'.format(content)) 
谢谢大家关注我的微博账号:小韩在BJ**

# 居中对齐
print('{:*^25}'.format(content)) 
***谢谢大家关注我的微博账号:小韩在BJ****

# 右对齐
print('{:*>25}'.format(content)) 
*******谢谢大家关注我的微博账号:小韩在BJ

# 浮点数的格式化  .nf
print('{:.3f}'.format(424.12134))
424.121

# 字符串的截断 .n
print('{:.10}'.format(content))
谢谢大家关注我的微博

4.做成函数

# 做成函数
def format_geshihua(content,length,filling='',align='^'):
    # content 格式化的内容  length为输出的字符串长度,filling为填充的内容  align为对齐方式
    return '{0:{1}{2}{3}}'.format(content,filling,align,length)


content='小韩在BJ'
print(format_geshihua(content,length=20))

       小韩在BJ        

print(format_geshihua(content,filling='*',align='<',length=10))
小韩在BJ*****

猜你喜欢

转载自www.cnblogs.com/xiaohaninBJ/p/10509485.html