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

本文详细介绍了使用Python生成各类随机数的方法,包括整数、浮点数、字符及字符串等,并提供了实例代码。同时,文章还展示了如何利用Python进行字符串的基本操作及列表的常见处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

	随机数

随机整数:

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
>>> import random
>>> 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' ] )
'two''three','two'
多个字符中选取特定数量的字符:

1
2
3
>>>  import  random
random.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] = 2001
print ("更新后的第三个元素为 : ", list[2])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值