Python generates random numbers, random string __python

Source: Internet
Author: User
Python produces random numbers, random strings




Import Random


#随机整数:
Print Random.randint (1,50)


#随机选取0到100间的偶数:
Print Random.randrange (0, 101, 2)


#随机浮点数:

Print Random.random ()
Print Random.uniform (1, 10)




#随机字符:
Print Random.choice (' abcdefghijklmnopqrstuvwxyz!@#$%^&* () ')




#多个字符中选取特定数量的字符:
Print random.sample (' ZYXWVUTSRQPONMLKJIHGFEDCBA ', 5)




#多个字符中选取特定数量的字符组成新字符串:
Prin '. Join (Random.sample) ([' Z ', ' y ', ' x ', ' W ', '] ' V ', ' u ', ') ' t ', ' s ', ' r ', ' Q ', ' P ', ' O ', ' n ', ' m ', ' l ', ' K ', ' j ', ' I ', ' h ', ' G ', ' F ' , ' e ', ' d ', ' C ', ' B ', ' A '], 5)




#随机选取字符串:
Print Random.choice ([' Scissors ', ' stone ', ' cloth '])




#打乱排序
Items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

Print Random.shuffle (items)



Here are four ways to implement Python string inversion:


1. Slices


def rev (s):


return S[::-1]


This is a slicing method, set the step to-1, which is the reverse sort.


This method is the most concise and most recommended.


2. This method is similar to slicing, but it is rather troublesome


def rev (s):


STR0 = "
L = Len (s)-1
While L >= 0:
STR0 + + s[l]
L-= 1
Return STR0





This method is to set a STR0 null variable first, then forward the value in S, then append to the STR0.


3. List


def rev (s):


A = List (s)
A.reverse ()
Return ". Join (a)


This method uses the reverse method of the list, first converts s to a list, then reverses it through the reverse method, and then joins the string through a join.


Note: Here, note the reverse and sort (or sorted) methods of the list:


Reverse is to sort the list direction;


Sort (reverse=true) is sorted in some order of direction.


Example


>>> a=[' A ', ' C ', ' B ', ' d ']
>>> b=[' A ', ' C ', ' B ', ' d ']
>>> A.sort (reverse=true)
>>> B.reverse ()
>>> A
[' d ', ' C ', ' B ', ' a ']
>>> b
[' d ', ' B ', ' C ', ' a ']


4. Reduce


def rev (s):


return reduce (lambda x, Y:y + x, s)

Related Article

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.