Python random number and random string

Source: Internet
Author: User
Random integer: & gt; importrandom & gt; randomrandint (100) 21: an even number ranging from 0 to: & gt; & gt; importrandom & gt; randomrandrange (0,101, 2) 42 random floating point random integer:

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

Randomly select an even number 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 randomrandom.sample('abcdefghij',3) ['a', 'd', 'b']

Select a specific number of 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)).replace(" ","")'fih'

Randomly selected string:

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


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

There are still many random functions, which are not listed here,

The above is a detailed description of Python random numbers and random strings. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.