python函数之杂货铺

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/lifanaugust/article/details/102767624

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

1、百分号方式 %[(name)][flags][width].[precision]typecode

常用格式化:

1

2

3

4

5

6

7

8

9

10

11

tpl = "i am %s" % "alex"

tpl = "i am %s age %d" % ("alex", 18)

tpl = "i am %(name)s age %(age)d" % {"name": "alex", "age": 18}

tpl = "percent %.2f" % 99.97623

tpl = "i am %(pp).2f" % {"pp": 123.425556, }

tpl = "i am %.2f %%" % {"pp": 123.425556, }

2、Format方式 [[fill]align][sign][#][0][width][,][.precision][type]

常用格式化:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

tpl = "i am {}, age {}, {}".format("seven", 18, 'alex')

  

tpl = "i am {}, age {}, {}".format(*["seven", 18, 'alex'])

  

tpl = "i am {0}, age {1}, really {0}".format("seven", 18)

  

tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18])

  

tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)

  

tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})

  

tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])

  

tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1)

  

tpl = "i am {:s}, age {:d}".format(*["seven", 18])

  

tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18)

  

tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18})

tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)

tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)

tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)

tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)

二 迭代器和生成器

1 迭代器

特点:

  1. 访问者不需要关心迭代器内部的结构,仅需通过next()方法不断去取下一个内容
  2. 不能随机访问集合中的某个值 ,只能从头到尾依次访问
  3. 访问到一半时不能往回退
  4. 便于循环比较大的数据集合,节省内存

2 生成器

如果函数中包含yield语法,那这个函数就会变成生成器

猜你喜欢

转载自blog.csdn.net/lifanaugust/article/details/102767624