Python3基础-字符串格式化

和自甴很熟 提交于 2019-12-01 08:41:51

原文来自  https://www.cnblogs.com/wupeiqi/articles/5484747.html

字符串格式化

Python的字符串格式化有两种方式: 百分号方式、format方式

百分号格式化

%[(name)][flags][width].[precision]typecode

  • (name)      可选,用于选择指定的key
  • flags          可选,可供选择的值有:width         可选,占有宽度
    • +       右对齐;正数前加正好,负数前加负号;

    • -        左对齐;正数前无符号,负数前加负号;

    • 空格    右对齐;正数前加空格,负数前加负号;

    • 0        右对齐;正数前无符号,负数前加负号;用0填充空白处

  • .precision   可选,小数点后保留的位数
  • typecode    必选
  1. s,获取传入对象的__str__方法的返回值,并将其格式化到指定位置
  2. r,获取传入对象的__repr__方法的返回值,并将其格式化到指定位置
  3. c,整数:将数字转换成其unicode对应的值,10进制范围为 0 <= i <= 1114111(py27则只支持0-255);字符:将字符添加到指定位置
  4. o,将整数转换成 八  进制表示,并将其格式化到指定位置
  5. x,将整数转换成十六进制表示,并将其格式化到指定位置
  6. d,将整数、浮点数转换成 十 进制表示,并将其格式化到指定位置
  7. e,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(小写e)
  8. E,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(大写E)
  9. f, 将整数、浮点数转换成浮点数表示,并将其格式化到指定位置(默认保留小数点后6位)
  10. F,同上
  11. g,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是e;)
  12. G,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是E;)
  13. %,当字符串中存在格式化标志时,需要用 %%表示一个百分号

注:Python中百分号格式化是不存在自动将整数转换成二进制表示的方式

name = "Susu"
age = 29
print("My name is %s ,age is %d"%(name,age))

format0="My name is %s"%"Susu0"   #打印字符串
print(format0)

format01="My name is "+"Susu0"+" "+"age is "+'19' #打印字符串
print(format01)

format1="My name is %s ,age is %d" % ("Susu1",29) #打印字符串、整数
print(format1)

format2="My name is %(name)s ,age is %(age)d" % {"name":"Susu1","age":29}
print(format2)

format30="price %f" % 12.9  #打印浮点数-默认7位小数点,后面补0
print(format30)

format3="price %.2f" % 12.93456  #打印浮点数(指定保留两位小数)
print(format3)

print("price %(price).2f" % {"price":99.123456})
print("price %(price).7f" % {"price":99.123456})#打印浮点数(指定保留7位小数)
print("price %(price).7f%%" % {"price":99.12})#打印百分比 %%
print("Name:%10s Age:%8d Height:%8.2f"%("Alfred",25,1.70))#打印指定占位符宽度,默认右对齐
print("Name:%-10s Age:%-8d Height:%-8.2f"%("Alfred",25,1.70))  #打印指定占位符宽度,左对齐
print("Name:%-10s Age:%08d Height:%-8.2f"%("Alfred",25,1.70)) #打印指定占位符宽度,左对齐
"""
执行结果如下
My name is Susu ,age is 29
My name is Susu0
My name is Susu0 age is 19
My name is Susu1 ,age is 29
My name is Susu1 ,age is 29
price 12.900000
price 12.93
price 99.12
price 99.1234560
price 99.1200000%
Name:    Alfred Age:      25 Height:    1.70
Name:Alfred     Age:25       Height:1.70    
Name:Alfred     Age:00000025 Height:1.70   
"""

Format方式

[[fill]align][sign][#][0][width][,][.precision][type]

  • fill           【可选】空白处填充的字符
  • align        【可选】对齐方式(需配合width使用)
    • <,内容左对齐
    • >,内容右对齐(默认)
    • =,内容右对齐,将符号放置在填充字符的左侧,且只对数字类型有效。 即使:符号+填充物+数字
    • ^,内容居中
  • sign         【可选】有无符号数字#            【可选】对于二进制、八进制、十六进制,如果加上#,会显示 0b/0o/0x,否则不显示
    • +,正号加正,负号加负;
    •  -,正号不变,负号加负;
    • 空格 ,正号空格,负号加负;
  • ,            【可选】为数字添加分隔符,如:1,000,000
  • width       【可选】格式化位所占宽度
  • .precision 【可选】小数位保留精度
  • type         【可选】格式化类型
  • 传入” 字符串类型 “的参数
    • s,格式化字符串类型数据
    • 空白,未指定类型,则默认是None,同s
  • 传入“ 整数类型 ”的参数
    • b,将10进制整数自动转换成2进制表示然后格式化
    • c,将10进制整数自动转换为其对应的unicode字符
    • d,十进制整数
    • o,将10进制整数自动转换成8进制表示然后格式化;
    • x,将10进制整数自动转换成16进制表示然后格式化(小写x)
    • X,将10进制整数自动转换成16进制表示然后格式化(大写X)
  • 传入“ 浮点型或小数类型 ”的参数
    • e, 转换为科学计数法(小写e)表示,然后格式化;
    • E, 转换为科学计数法(大写E)表示,然后格式化;
    • f , 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
    • F, 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
    • g, 自动在e和f中切换
    • G, 自动在E和F中切换
    • %,显示百分比(默认显示小数点后6位)
    • print("My name is {}, age {}, {}".format("one", 29, 'susu'))
      print("My name is {}, age {}, {}".format(*["one", 29, 'susu']))
      #print("My name is {}, age {}, {}".format("one", 29)) #没有一一对应,则报错IndexError: tuple index out of range
      print("My name is {}, age {}, {}".format("one", 29,'two',30)) #超出范围,则只读取前三个 My name is one, age 29, two
      
      print("My name is {0}, age {1}, really {0}".format("one", 29,))
      print("My name is {0}, age {1}, really {0}".format(*["one", 29]))
      #print("i am {0}, age {1}, really {2}".format("seven", 18))  #报错  IndexError: tuple index out of range
      #print("i am {0}, age {1}, really {2}".format(*["seven", 18])) #报错 IndexError: tuple index out of range
      
      print("My name is {name}, age {age}, really {name}".format(name="noe", age=18))
      #print("My name is {name}, age {age}, really {name}".format(name="noe"))  #KeyError: 'age'
      print("My name is {name}, age {age}, really {name}".format(name="noe", age=18))
      print("My name is {name}, age {age}, really {name}".format(**{"name": "noe", "age": 18}))
      
      print("My name is {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33]))
      print("My name is {1[0]}, age {1[1]}, really {1[2]}".format([1, 2, 3], [11, 22, 33]))
      
      print("My name is {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1))
      #  print("My name is {:s}, age {:d}, money {:f}".format(19, "Susu", 88888.1)) #报错 ValueError: Unknown format code 's' for object of type 'int'
      print("My name is {:s}, age {:d}".format(*["seven", 18]))
      
      print("My name is {name:s}, age {age:d}".format(name="seven", age=18))
      print("My name is {name:s}, age {age:d}".format(**{"name": "seven", "age": 18}))
      
      print("numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623))
      print("numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623))
      
      print("numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15))
      print("numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15))
      
      """
      执行结果
      My name is one, age 29, susu
      My name is one, age 29, susu
      My name is one, age 29, two
      My name is one, age 29, really one
      My name is one, age 29, really one
      My name is noe, age 18, really noe
      My name is noe, age 18, really noe
      My name is noe, age 18, really noe
      My name is 1, age 2, really 3
      My name is 11, age 22, really 33
      My name is seven, age 18, money 88888.100000
      My name is seven, age 18
      My name is seven, age 18
      My name is seven, age 18
      numbers: 1111,17,15,f,F, 1587.623000%
      numbers: 1111,17,15,f,F, 1587.623000%
      numbers: 1111,17,15,f,F, 1500.000000%
      numbers: 1111,17,15,f,F, 1500.000000%
      """

       

拼接

#拼接
print('my','name','is',sep=' ') #用空格拼接
print('my','name','is',sep='-') #用-拼接
print('my '+'name '+'is' )
"""
执行结果
my name is
my-name-is
my name is
"""

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!