Python3 choice() Function
Description
choice()The method returns a random item from a list, tuple, or string.
Syntax
The following is the syntax for the choice() method:
import random random.choice( seq )
Note:choice() cannot be accessed directly. You need to import the random module, and then call the method via the random static object.
Parameters
- seq -- Can be a list, tuple, or string.
Return Value
Returns a random item.Example
The following shows an example of using the choice() method:
Example
import random
print ("Returns a random number from range(100): ",random.choice(range(100)))
print ("Returns a random element from the list [1, 2, 3, 5, 9]): ", random.choice([1, 2, 3, 5, 9]))
print ("Returns a random character from the string 'Example': ", random.choice('Example'))
The output of the above example after running is:
从 range(100) 返回一个随机数 : 68 从列表中 [1, 2, 3, 5, 9]) 返回一个随机元素 : 2 从字符串中 'Example' 返回一个随机字符 : u
The following is a simple implementation of a random password generator:
Example
import string
def generate_password(length):
# Define the set of characters available for the password
chars = string.ascii_letters + string.digits + string.punctuation
# Randomly select characters to generate the password
password = ''.join(random.choice(chars) for _ in range(length))
return password
random_pwd = generate_password(6) # Output length is 6
print(random_pwd)
In the above example,generate_password()The function accepts an integer parameter length, which indicates the length of the password to be generated, and then uses the random and string modules from the Python standard library to generate a random password.string.ascii_lettersContains all letters (uppercase and lowercase),string.digitsContains all digits,string.punctuationContains all punctuation marks.
random.choice(chars) randomly selects a character from the character set chars, and then the join() method concatenates the generated characters together to form the password.
The output of the above example after running is:
R?u|<KOther Extensions