concepts and notations
concepts
- 字符串不可变;
notations
%s |
转换说明符,将指定值转换为字符串类型 |
%.3f |
带有3位小数的浮点数 |
设置字符串格式
method1:格式设置运算符%
- 针对单个值(string or number)
- 针对多个值(tuple)
>>> format = "Hello, %s. %s enought for ya?"
>>> values = ('world', 'Hot')
>>> format % values
method2:字符串方法format
# 待替换字段-无名称
>>> "{}, {} and {}".format("first", "second", "third")
'first, second, third'
# 待替换字段-以索引为名称
>>> "{0}, {1} and {2}".format("first", "second", "third")
'first, second and third'
>>> "{3}, {0}, {2}, {1}, {3}, {0}".format("be", "not", "or", "to")
'to be or not to be'
# 替换多个字段,参数顺序无关紧要
# 指定格式说明符.2f(带有2位小数的浮点数),用冒号将格式说明符与字段名隔开
>>> from math import pi
>>> "{name} is approximately {value: .2f}.".format(value = pi, name = "pi")
# 变量与待替换字段同名,可使用f字符串(f"")
>>> from math import e
>>> f"Eluer's constant is roughly {e}"
>>> "Eluer's constant is rougtly 2.718281828459045"
网友评论