Python common random number and random string method instance _python

Source: Internet
Author: User
Tags shuffle

Random integer:

Copy Code code as follows:

>>> Import Random
>>> Random.randint (0,99)
21st

randomly select an even number between 0 and 100:
Copy Code code as follows:

>>> Import Random
>>> random.randrange (0, 101, 2)
42

Random floating-point numbers:
Copy Code code as follows:

>>> Import Random
>>> Random.random ()
0.85415370477785668
>>> random.uniform (1, 10)
5.4221167969800881

Random characters:
Copy Code code as follows:

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

Select a specific number of characters in more than one character:
Copy Code code as follows:

>>> Import Random
Random.sample (' Abcdefghij ', 3)
[' A ', ' d ', ' B ']

Select a specific number of characters to compose a new string in more than one character:
Copy Code code as follows:

>>> Import Random
>>> Import String
>>> String.Join (Random.sample ([' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' J '], 3)). R
Eplace ("", "")
' FIH '

Random Pick String:
Copy Code code as follows:

>>> Import Random
>>> random.choice ([' Apple ', ' pear ', ' peach ', ' orange ', ' Lemon '])
' Lemon '

Shuffle:
Copy Code code as follows:

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

There are a lot of random functions that are not listed here,
References: http://docs.python.org/lib/module-random.html

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: info-contact@alibabacloud.com 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.