zlzyp 发表于 2018-8-8 11:50:31

python3_03.数据类型

  
#python字符串格式化:
  
   "this is %d %s bird" % (1, 'dead')             # 一般的格式化表达式
  
   "%s---%s---%s" % (42, 3.14, )          # 字符串输出:'42---3.14---'
  
   "%d...%6d...%-6d...%06d" % (1234, 1234, 1234, 1234) # 对齐方式及填充:"1234...1234...1234...001234"
  
   x = 1.23456789
  
   "%e | %f | %g" % (x, x, x)               # 对齐方式:"1.234568e+00 | 1.234568 | 1.23457"
  
   "%6.2f*%-6.2f*%06.2f*%+6.2f" % (x, x, x, x)      # 对齐方式:'1.23*1.23*001.23* +1.23'
  
   "%(name1)d---%(name2)s" % {"name1":23, "name2":"value2"}    # 基于字典的格式化表达式
  
   "%(name)s is %(age)d" % vars()               # vars()函数调用返回一个字典,包含了所有本函数调用时存在的变量
  
"{0}, {1} and {2}".format('spam', 'ham', 'eggs')    # 基于位置的调用
  
   "{motto} and {pork}".format(motto = 'spam', pork = 'ham')   # 基于Key的调用
  
   "{motto} and {0}".format(ham, motto = 'spam')            # 混合调用
  
   # 添加键 属性 偏移量 (import sys)
  
   "my {1} runs {0.platform}".format(sys, {'spam':'laptop'})      # 基于位置的键和属性
  
   "{config} {sys.platform}".format(sys = sys, config = {'spam':'laptop'})   # 基于Key的键和属性
  
   "first = {0}, second = {0}".format(['A', 'B', 'C'])         # 基于位置的偏移量
  
   # 具体格式化
  
   "{0:e}, {1:.3e}, {2:g}".format(3.14159, 3.14159, 3.14159)   # 输出'3.141590e+00, 3.142e+00, 3.14159'
  
    "{fieldname:format_spec}".format(......)
  
   # 说明:
  
   """
  
       fieldname是指定参数的一个数字或关键字, 后边可跟可选的".name"或""成分引用
  
       format_spec ::=[align][#][,][.precision]
  
       fill      ::=<any character>            #填充字符
  
       align       ::="<" | ">" | "=" | "^"      #对齐方式
  
       sign      ::="+" | "-" | " "            #符号说明
  
       width       ::=integer                      #字符串宽度
  
       precision   ::=integer                      #浮点数精度
  
       type      ::="b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
  
   """
  
   # 例子:
  
       '={0:10} = {1:10}'.format('spam', 123.456)    # 输出'=spam       =    123.456'
  
       '={0:>10}='.format('test')                  # 输出'=      test='
  
       '={0:<10}='.format('test')                  # 输出'=test      ='
  
       '={0:^10}='.format('test')                  # 输出'=   test   ='
  
       '{0:X}, {1:o}, {2:b}'.format(255, 255, 255)   # 输出'FF, 377, 11111111'
  
       'My name is {0:{1}}.'.format('Fred', 8)       # 输出'My name is Fred    .'动态指定参数
页: [1]
查看完整版本: python3_03.数据类型