深度阅读

Python generate random number and string

作者
作者
2023年08月22日
更新时间
11.15 分钟
阅读时间
0
阅读量

To generate a random number in Python, you can use the random module. The random module provides various functions for generating random numbers of different types. Here is an example code that generates a random integer between 1 and 100:

import random

random_number = random.randint(1, 100)
print(random_number)

This will output a random integer between 1 and 100.

To generate a random string in Python, you can use the string and random modules. The string module provides various string constants, such as letters, digits, and punctuation. The random module provides various functions for generating random elements from a sequence.

Here is an example code that generates a random string of length 8, consisting of lowercase letters:

import random
import string

random_string = ''.join(random.choice(string.ascii_lowercase) for i in range(8))
print(random_string)

This will output a random string of length 8, consisting of lowercase letters.

Note that the secrets module can also be used to generate cryptographically secure random numbers and strings in Python.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。