
c罗
format()基本用法
Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
基本语法是通过 {} 和 : 来代替以前的 % 。
format 函数可以接受不限个参数,位置可以不按顺序。
>>> a = "名字是:{0},年龄是:{1}"
>>> a.format("攻城狮",20)
'名字是:攻城狮,年龄是:20'
>>> b = "名字是:{name},年龄是:{age}"
>>> b.format(age = 22,name="工程师")
'名字是:工程师,年龄是:22'
通过{索引}/{参数名},直接映射参数值,实现对字符串的格式化
填充与对齐
填充常跟对齐一起使用
^、<、>分别是居中、左对齐、右对齐,后面带宽度
:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充
>>> "{:*>8}".format("245")
'*****245'
>>> "{0:*^8}".format("666")
'**666***'
数字格式化
浮点数通过 f,整数通过 d 进行需要的格式化。
>>> a = "我是{0},我的存款有{1:.2f}"
>>> a.format("工程师",168.234342)
'我是工程师,我的存款有168.23'
其他格式,供参考:

其他格式
可变字符串
在 Python 中,字符串属于不可变对象,不支持原地修改,如果需要修改其中的值,只能创建新的字符串对象。但是,经常我们确实需要原地修改字符串,可以使用 io.StringIO对象或 array 模块。
>>> s = "hello,gcs"
>>> sio = io.StringIO(s)
Traceback (most recent call last):
  File "<pyshell#49>", line 1, in <module>
    sio = io.StringIO(s)
NameError: name 'io' is not defined
>>> import io
>>> sio = io.StringIO(s)
>>> sio
<_io.StringIO object at 0x0000018F34DA7D38>
>>> sio.getvalue()
'hello,gcs'
>>> sio.seek(7)
7
>>> sio.write("g")
1
>>> sio.getvalue()
'hello,ggs'