随机数
随机整数:
1 2 3 | >>> import random>>> random.randint(0,99)21 |
随机选取0到100间的偶数:
1 2 3 | >>> import random>>> random.randrange(0, 101, 2)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 | >>> random.uniform(a, b)
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'] ) |
1 2 3 | >>> import randomrandom.sample('abcdefghij',3) ['a', 'd', 'b'] |
字符串n = 1 print(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] = 2001print ("更新后的第三个元素为 : ", list[2])
本文详细介绍了使用Python生成各类随机数的方法,包括整数、浮点数、字符及字符串等,并提供了实例代码。同时,文章还展示了如何利用Python进行字符串的基本操作及列表的常见处理。
542

被折叠的 条评论
为什么被折叠?



