【flag】 python 格式化字符 and help用法

python格式化应用 

九九乘法表:

1 def printLine(row):
2     for col in range(1,row+1):
3         print(row*col,end=' ')
4     print('')
5 
6 for row in range(1,10):
7     printLine(row)

执行结果:

1 
2 4 
3 6 9 
4 8 12 16 
5 10 15 20 25 
6 12 18 24 30 36 
7 14 21 28 35 42 49 
8 16 24 32 40 48 56 64 
9 18 27 36 45 54 63 72 81 

注意到由于有的数字仅有一位 有的两位 我的乘法表没对齐 好难看!!!

 

修改:

1 def printLine(row):
2     for col in range(1,row+1):
3         print('{0:2}'.format(row*col),end=' ')
4     print('')
5 
6 for row in range(1,10):
7     printLine(row)

 

执行结果:

 1 
 2  4 
 3  6  9 
 4  8 12 16 
 5 10 15 20 25 
 6 12 18 24 30 36 
 7 14 21 28 35 42 49 
 8 16 24 32 40 48 56 64 
 9 18 27 36 45 54 63 72 81

 

利用 format()函数进行格式化

取位数“{:2}”、"{:.2f}"等 #分别表示 保留两位数字 /小数点后保留两位数字 

- 格式化字符参考文章:

  https://www.cnblogs.com/fat39/p/7159881.html

 

一些细节 :

  1.  end=' '  

    - print 打印完成后默认换行(默认参数)

    - 关于参数的查找与修改:

      - 利用help()函数 

help(print)

      结果:

Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

     据此修改参数

 

  2.print('')   (代码块第四行)

  再次利用print的默认参数仅进行换行

 

  3.函数是个好东西 在重复型任务方面

posted @ 2018-08-03 14:46  鸟茫然  阅读(613)  评论(0编辑  收藏  举报