Python commonly USES random number and random string method instances

  • 2020-05-07 20:00:17
  • OfStack

random integer:


>>> import random
>>> random.randint(0,99)
21

randomly selects even Numbers between 0 and 100:

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

random floating point number:

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

random characters:

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

Select a specific number of characters from multiple characters:

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

Select a specific number of characters from 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'

randomly selects strings:

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

shuffling:

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

There are many more functions for random, not 11 here,
Resources: http: / / docs python. org lib/module - random. html


Related articles: