format函数基本用法

  • Post author:
  • Post category:其他

1.format函数基本格式:<模块字符>.format(<逗号分隔的参数>)

例如:

print("{},我想跟你说:{}“.format(a,b))

2.字符串format()方法。例如:

print("{} {}".format("hello","world"))#不指定位置

运行结果为 hello world

print("{1} {0}{1}".format("hello","world"))#设置指定位置

运行结果为 world helloworld

print("网站:{s} ,地址:{u}".format(s="hello",u="world")) #参数指定

运行结果为:网站:hello ,地址:world

3.字符串格式控制信息

槽的内部样式如下:

{<参数序号>:<格式控制标记>}

例如:

print('{0:2}' .format('abc')) #宽度不够按实际显示

输出结果为:abc

print('{0:>11}'.format("abc")) #右对齐,左补8个空格

输出结果为: abc

print('{0:=^11}'.format("abc")) #居中对齐,左右各补4个二

输出结果为:====abc====

练习如下:

a="python"
b=" a super language"
print("{:->10}:{:-<19}".format(a,b))

结果为:—-python: a super language–


版权声明:本文为minghaibuai原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。