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)