Python3 choice() Function
Description
choice() The method returns a random item from a list, tuple, or string.
Syntax
The syntax of the choice() method is as follows:
import random
random.choice( seq )
**Note:** choice() cannot be accessed directly; you need to import the random module and call the method through the static random object.
Parameters
- seq -- can be a list, tuple, or string.
Return Value
Returns a random item.
Example
The following shows examples of using the choice() method:
Example
#!/usr/bin/python3
import
random
(
"Return a random number from range(100): "
,
random
.
choice
(
range
(
100
)
)
)
(
"Return a random element from the list [1, 2, 3, 5, 9]): "
,
random
.
choice
(
[
1
,
2
,
3
,
5
,
9
]
)
)
(
"Return a random character from the string 'Runoob': "
,
random
.
choice
(
'Runoob'
)
)
Running the example above produces:
从 range(100) 返回一个随机数 : 68
从列表中 [1, 2, 3, 5, 9]) 返回一个随机元素 : 2
从字符串中 'Runoob' 返回一个随机字符 : u
Below is a simple implementation of a random password generator:
Example
import
random
import
string
def
generate_password
(
length
)
:
Define the set of characters available for passwords
chars
=
string
.
ascii_letters
string
.
digits
string
.
punctuation
Randomly select characters to generate a password
password
=
''
.
join
(
random
.
choice
(
chars
)
for
_
in
range
(
length
)
)
return
password
random_pwd
=
generate_password
(
6
)
Output length is 6
(
random_pwd
)
In the example above, the generate_password() function takes an integer parameter length representing the password length to generate, then uses the random and string modules from the Python standard library to generate a random password.string.ascii_letters Contains all letters (uppercase and lowercase),string.digits contains all digits,string.punctuation contains all punctuation characters.
random.choice(chars) randomly selects one character from the character set chars, then the join() method joins the generated characters together to form the password.
Running the example above produces:
R?u|
Python3 Numbers