Detailed explanation of Python random numbers and random strings

高洛峰
Release: 2017-03-16 17:28:48
Original
1816 people have browsed it

Random integer:

>>> import random
>>> random.randint(0,99)
21
Copy after login

Randomly select an even number between 0 and 100:

>>> import random
>>> random.randrange(0, 101, 2)
42
Copy after login

Random floating point number:

>>> import random
>>> random.random() 
0.85415370477785668
>>> random.uniform(1, 10)
5.4221167969800881
Copy after login

Random character:

>>> import random
>>> random.choice('abcdefg&#%^*f')
'd'
Copy after login

Select a specific number of characters from multiple characters:

>>> import random
random.sample('abcdefghij',3) 
['a', 'd', 'b']
Copy after login

Select a specific number of characters from multiple characters to form a new string:

>>> import random
>>> import string
>>> string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)).r
eplace(" ","")
'fih'
Copy after login

Select a random string:

>>> import random
>>> random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )
'lemon'
Copy after login

Shuffle:

>>> import random
>>> items = [1, 2, 3, 4, 5, 6]
>>> random.shuffle(items)
>>> items
[3, 2, 5, 6, 4, 1]
Copy after login

There are many functions of random, so I won’t list them all here,

The above is the detailed content of Detailed explanation of Python random numbers and random strings. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!