1:已知a和b元素
a = "pyer"
b = "apple"
用字典和format方法实现:效果:my name is pyer, i love apple.
1、format的方法
c ="mysql name is {0},i love {1}".format("pyer","apple")
用字典的方法:
>>> c ="mysql name is {xiaoluo},i love {hui}".format(xiaoluo="pyer",hui="apple")
>>> c
"mysql name is pyer,i love apple"
#主要是理解占位符的概念。
二、string模块的操作:
1.包含0-9的数字。
>>> import string
>>> string.digits
"0123456789"
2.所有小写字母。
>>> string.ascii_lowercase
"abcdefghijklmnopqrstuvwxyz"
3.所有标点符号。
string.printable
4.所有大写字母和小写字母。
>>> string.letters
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
三、已知字符串:a = "i,am,a,boy,in,china"求出am的位置,主要考察index方法,计算有多少个逗号,
>>> s =a.split(",")
>>> s
["i", "am", "a", "boy", "in", "china"]
>>> s.index("am")
三、(2)
>>> len(s) - 1
5
#这里用,号分割,那么任何分割的东西个数,等于len(x) - 1 (x表示列表)
四、
(1)列表切割a=[1,3,5,6,7]要求输出结果为:5,6
>>> a =[1,3,5,6,7]
>>> x = a[2:4:1]
>>> x
[5, 6]
#2表示从第二个开始切割,4表示到第四位的前面结束,1表示步长,根据自己来定
(2)用列表推导式生成100内的大于20的偶数
>>> [x for x in range(0,101) if x>20 if x%2!=1]
#主要是%2取余
四、(3)输出结果[1 love python,2 love python,3 love python,.... 10 love python]
>>> ["%s love python"%(x) for x in range(0,10)]
(4)输出结果:[(0,0),(0,2),(2,0),(2,2)]
[(x,y) for x in (0,2) for y in (0,2)]
五、集合的基本用法:
集合的交集,并集,差集:
>>> a = set("abcd")
>>> b = set("bcdef")
>>> a & b
set(["c", "b", "d"])
>>> a | b
set(["a", "c", "b", "e", "d", "f"])
>>> a - b
set(["a"])
去除重复元素:
>>> a = [1,3,4,1,]
>>> a
[1, 3, 4, 1]
>>> b = set(a)
>>> b
set([1, 3, 4])
>>>
集合增加元素,然后再转换成列表:
>>> b.add("python")
>>> b
set(["a", "python", "c", "b"])
六:
已知字典:ainfo = {"ab":"liming","ac":20}
两种发放输出如下结果:
ainfo = {"ab":"liming","ac":20,"sex":"man","age":20}
第一・赋值法:
>>> ainfo = {"ab":"liming","ac":20}
>>> ainfo["sex"]="man"
>>> ainfo["age"]=20
>>> ainfo
{"ac": 20, "ab": "liming", "age": 20, "sex": "man"}
第二、update方法:
>>> ainfo
{"ac": 20, "ab": "liming", "age": 20, "sex": "man"}
2 输出结果:["ab","ac"]
>>> ainfo.keys()
["ac", "ab"]
3 输出结果:["liming",20]
>>> ainfo.values()
[20, "liming"]
>>> ainfo.values()[::-1]
["liming", 20]
4、 通过2个方法删除键名ac对应的值。
>>> ainfo.pop("ac")
20
>>> ainfo
{"ab": "liming"}
七、数据的排序:
>>> a.sort()
>>> a
[11, 22, 24, 28, 29, 30, 32, 57]