python学习/2021/1/7_day3_zhou125disorder

字符串的格式化

  1. format()的使用方法;
这是format的两种使用方法
>>> value="我的名字叫{1}年龄{2}"
>>> value.format("卡卡西",30)
Traceback (most recent call last):
  File "<pyshell#91>", line 1, in <module>
    value.format("卡卡西",30)
IndexError: Replacement index 2 out of range for positional args tuple

>>> value="我的名字叫{0}年龄{1}"
>>> value.format("卡卡西",30)
'我的名字叫卡卡西年龄30'

>>> value="我的名字叫{name}年龄{age}"
>>> value.format(name="卡卡西",age=18)
'我的名字叫卡卡西年龄18'
  1. 填充与对齐

^、<、>分别是居中、左对齐、右对齐,后面带宽度

>>> "{:^8}".format("卡卡西")
'  卡卡西   '
>>> "我的名字叫{0}年龄{1:*>8}".format("卡卡西","30")
'我的名字叫卡卡西年龄******30'
  1. 数字格式化

such

>>> value="我的工资{0:.2f}"
>>> value.format(9000)
'我的工资9000.00'
3.14159265357989		{
    
    :.2f}		3.14		保留小数点后两位 
3.14159265357989		{
    
    :+.2f}		3.14		带符号保留小数点后两位 
2.718281828		{
    
    :.0f}		3		不带小数 
4		{
    
    :0>2d}		04		数字补零(填充左边, 宽度为 2) 
4		{
    
    :x<4d}		4xxx		数字补x(填充右边, 宽度为 4) 
12		{
    
    :x<4d}		12xx		数字补x(填充右边, 宽度为 4) 
1000000		{
    
    :,}		1,000,000		以逗号分隔的数字格式 
0.25		{
    
    :.2%}		25.00%		百分比格式 
100000000		{
    
    :.2e}		1.00E+08		指数记法 
4 		{
    
    :10d} 			4右对齐(默认, 宽度为 10) 
4 		{
    
    :<10d} 4 		左对齐 		(宽度为 10)
4 		{
    
    :^10d} 	4 	中间对齐 (宽度为 10)

可变字符串

================== RESTART: Shell ==================
>>> import io
>>> content="我的名字叫卡卡西"
>>> contentio = io.StringIO(content)
>>> contentio
<_io.StringIO object at 0x0000029156846AF0>
>>> contentio.getvalue()
'我的名字叫卡卡西'
>>> contentio.seek(5)
5
>>> contentio.write("我")
1
>>> contentio.getvalue()
'我的名字叫我卡西'

猜你喜欢

转载自blog.csdn.net/ZHOU125disorder/article/details/112319836