str.format():格式化字符串的函数,通过{} 和 :来代替以前的 % 。

str.format()用法说明 格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

基本语法是通过{} 和 :来代替以前的 % 。【真的巨巨巨方便】

【例】

str.format()可以接受不限个参数,位置可以不按顺序。

print("{} {}".format("hello", "world"))  #不设置指定位置,按默认顺序
print("{0} {1}".format("hello", "world"))  #设置指定位置
print( "{1} {0} {1}".format("hello", "world"))  # 设置指定位置
  • 1.
  • 2.
  • 3.

str.format()可以设置参数、通过字典设置参数、通过列表索引设置参数

print('{0},{1}'.format('xpt', 18))
print('{},{},{}'.format('xpt', 'fm', 18))

#可以设置参数
print('{name},{sex},{age}'.format(age=18, sex='fm', name='xpt'))

# 通过字典设置参数
site = {'name': 'xpt', 'url': 'https://xxpt.github.io/xxpt.github.io/'} # 字典dict格式 {'key':vale}
print("Author:{name}, Blog: {url}".format(**site))

# 通过列表索引设置参数
my_list = ['xpt', 'https://xxpt.github.io/xxpt.github.io/']
print("Author:{0[0]}, Blog: {0[1]}".format(my_list))  # "0" 是必须的
my_list2 = ['baidu','https://www.baidu.com/']
print("sitename:{1[0]}, url: {1[1]}".format(my_list,my_list2))
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

可以向 str.format() 传入对象

class authorage(object):
    def __init__(self, value):
        self.value = value

author_age = authorage(18)
print('Author age: {0.value}'.format(author_age))
# 0可以去掉,0表示format函数里第一个对象,.value取属性值
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

1、精度格式化

print("{:.2f}".format(3.1415926))#保留小数点后两位
print("{:+.3f}".format(3.1415926))#带符号保留小数点后两位
print("{:.0f}".format(-3.1415926))#不带小数
  • 1.
  • 2.
  • 3.

2、b、d、o、x分别是二进制、十进制、八进制、十六进制

print('{:b}'.format(11))
print('{:d}'.format(11))
print('{:o}'.format(11))
print('{:x}'.format(11))
  • 1.
  • 2.
  • 3.
  • 4.

3、以逗号分隔的数字、百分比格式、指数记法

print("{:,}".format(100000))#以逗号分隔的数字
print("{:.2%}".format(0.23456))#百分比格式
print("{:.2e}".format(0.23456))#指数记法
  • 1.
  • 2.
  • 3.


 https://blog.csdn.net/qq_34243930/article/details/106531570