python3中随机数,字符串,列表笔记

来源:互联网 发布:网络端游排行榜2015 编辑:程序博客网 时间:2024/06/07 06:09
随机数

随机整数:

1
2
3
>>> import random
>>> random.randint(0,99)
21

随机选取0到100间的偶数:

1
2
3
>>> import random
>>> random.randrange(01012)
42

随机浮点数:实现0到1之间的小数,包括0但不包括1,乘一个数可以强转整形,缺点代码比较麻烦

1
2
3
4
5
>>> import random
>>> random.random() 
0.85415370477785668
>>> import random
>>> random.random()*10+1
  6.54567894160123462

随机字符:生成a,b之间的随机浮点数,与randint不同的是a,b无需是整数,也不用考虑大小,并且b不会随机出现

1
2
3
>>> import random
>>> random.uniform(ab)
  5.4221167969800881
  2

随机字符:在指定范围内随机取样一个

1
2
3
>>> import random
>>> random.choice(range(1,3))
2

随机选取字符串:在指定范围你随机取样多个,可以重复出现同一个字符

1
2
3
>>> import random
>>> random.choices ( ['one''two''three''four''five'] )
'two''three','two'
多个字符中选取特定数量的字符:

1
2
3
>>> import random
random.sample('abcdefghij',3
['a''d''b']


字符串
n = 1print(str(n)+"10") print(n.__str__()+"15") #转换为字符串 str = "爱我爱中国爱"--------------------常用的 print('爱' in str) #判断 爱 是否在字符串中 print(str.index('爱')) #找不到会报错 print(str.replace('爱','哎')) #字符串替换 print(str.endswith('国')) #以‘ ’结尾的字符串 存在返回 true 否则 false print(str[2:3])#输出具体的下标的字符串 print(str[2:]) # 输出具体的下标的字符串之结束 print(str*2) #两倍输出(可以为n倍)
 print("hello"+"python")#字符串的拼接
列表

创建列表:

list1 = ['Google', 'Runoob', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
访问列表:

list1 = ['Google', 'Runoob', 1997, 2000]

list2 = [1, 2, 3, 4, 5, 6, 7 ]

print ("list1[0]: ", list1[0])

print ("list2[1:5]: ", list2[1:5]

更新列表:

list = ['Google', 'Runoob', 1997, 2000] 

print ("第三个元素为 : ", list[2])

list[2] = 2001

print ("更新后的第三个元素为 : ", list[2])

删除列表:

list = ['Google', 'Runoob', 1997, 2000] 
print ("第三个元素为 : ", list[2])
list[2] = 2001
print ("更新后的第三个元素为 : ", list[2])
原创粉丝点击