Hướng dẫn how do you generate a random character in python? - làm thế nào để bạn tạo một ký tự ngẫu nhiên trong python?

#*A handy python password generator*

Đây là đầu ra

Show
 import random
    letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
        
    print("Welcome to the Python Password Generator!")
    l= int(input("How many letters would you like in your password?\n")) 
    s = int(input(f"How many symbols would you like?\n"))
    n = int(input(f"How many numbers would you like?\n"))
        
    sequence = random.sample(letters,l)
    num      = random.sample(numbers,n)
    sym      = random.sample(symbols,s)
    sequence.extend(num)
    sequence.extend(sym)
         
    random.shuffle(sequence)
    password = ''.join([str(elem) for elem in sequence])#listToStr 
    print(password)

Trong bài học này, bạn sẽ học cách tạo một chuỗi và mật khẩu ngẫu nhiên trong Python.

Hằng số chuỗi

Dưới đây là danh sách các hằng số chuỗi bạn có thể sử dụng để lấy một bộ ký tự khác làm nguồn để tạo một chuỗi ngẫu nhiên.

Không thay đổiSự mô tả
import random
import string

def get_random_string(length):
    # choose from all lowercase letter
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Random string of length", length, "is:", result_str)

get_random_string(8)
get_random_string(6)
get_random_string(4)
3
Chứa tất cả các chữ cái viết thường
import random
import string

def get_random_string(length):
    # choose from all lowercase letter
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Random string of length", length, "is:", result_str)

get_random_string(8)
get_random_string(6)
get_random_string(4)
4
Chứa tất cả các chữ cái viết hoa
import random
import string

def get_random_string(length):
    # choose from all lowercase letter
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Random string of length", length, "is:", result_str)

get_random_string(8)
get_random_string(6)
get_random_string(4)
5
Chứa cả chữ thường và chữ hoa
import random
import string

def get_random_string(length):
    # choose from all lowercase letter
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Random string of length", length, "is:", result_str)

get_random_string(8)
get_random_string(6)
get_random_string(4)
6
Chứa các chữ số ‘0123456789.
import random
import string

def get_random_string(length):
    # choose from all lowercase letter
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Random string of length", length, "is:", result_str)

get_random_string(8)
get_random_string(6)
get_random_string(4)
7
Tất cả các biểu tượng đặc biệt
import random
import string

def get_random_string(length):
    # choose from all lowercase letter
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Random string of length", length, "is:", result_str)

get_random_string(8)
get_random_string(6)
get_random_string(4)
8
import random
import string

def get_random_string(length):
    # choose from all lowercase letter
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Random string of length", length, "is:", result_str)

get_random_string(8)
get_random_string(6)
get_random_string(4)
9
Bao gồm không gian ký tự, tab, linefeed, return, formFeed và tab dọc
Random string of length 8 is: ijarubtd
Random string of length 6 is: ycfxbs
Random string of length 4 is: dpla
0
Random string of length 8 is: ijarubtd
Random string of length 6 is: ycfxbs
Random string of length 4 is: dpla
1
Các ký tự được coi là có thể in. Đây là sự kết hợp của các hằng số
import random
import string

def get_random_string(length):
    # choose from all lowercase letter
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Random string of length", length, "is:", result_str)

get_random_string(8)
get_random_string(6)
get_random_string(4)
6,
Random string of length 8 is: ijarubtd
Random string of length 6 is: ycfxbs
Random string of length 4 is: dpla
3,
import random
import string

def get_random_string(length):
    # choose from all lowercase letter
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Random string of length", length, "is:", result_str)

get_random_string(8)
get_random_string(6)
get_random_string(4)
7 và
import random
import string

def get_random_string(length):
    # choose from all lowercase letter
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Random string of length", length, "is:", result_str)

get_random_string(8)
get_random_string(6)
get_random_string(4)
9.
Hằng số chuỗi

Cách tạo một chuỗi ngẫu nhiên trong Python

Chúng ta có thể tạo chuỗi ngẫu nhiên bằng mô -đun ngẫu nhiên và mô -đun chuỗi. Sử dụng các bước dưới đây để tạo một chuỗi ngẫu nhiên có bất kỳ độ dài nào trong Python.

  1. Nhập chuỗi và mô -đun ngẫu nhiên

    Mô -đun chuỗi chứa hằng số chuỗi khác nhau chứa các ký tự ASCII của tất cả các trường hợp. Nó có các hằng số riêng biệt cho chữ thường, chữ hoa, chữ số và các ký hiệu đặc biệt mà chúng ta sử dụng làm nguồn để tạo ra một chuỗi ngẫu nhiên.
    Pass string constants as a source of randomness to the random module to create a random string

  2. Sử dụng Chuỗi Hằng số ASCII_LowerCase

    Random string of length 8 is: ijarubtd
    Random string of length 6 is: ycfxbs
    Random string of length 4 is: dpla
    6 trả về một danh sách tất cả các chữ cái viết thường từ ‘A, đến‘ Z. Dữ liệu này sẽ được sử dụng làm nguồn để tạo các ký tự ngẫu nhiên.source to generate random characters.

  3. Quyết định độ dài của một chuỗi

    Quyết định có bao nhiêu ký tự bạn muốn trong chuỗi kết quả.

  4. Sử dụng hàm For Loop và Random Choice () để chọn các ký tự từ nguồn

    Chạy một vòng lặp cho đến khi độ dài chuỗi quyết định và sử dụng chức năng Random Choice () & NBSP; trong mỗi lần lặp để chọn một ký tự duy nhất từ ​​hằng số chuỗi & nbsp; và thêm nó vào biến chuỗi bằng A & nbsp; ________ 37 & nbsp; function. In chuỗi cuối cùng sau cuộc thi vòng lặpin each iteration to pick a single character from the string constant and add it to the string variable using a 

    Random string of length 8 is: ijarubtd
    Random string of length 6 is: ycfxbs
    Random string of length 4 is: dpla
    7 function. print the final string after loop competition

  5. Tạo mật khẩu ngẫu nhiên

    Sử dụng hằng số

    Random string of length 8 is: ijarubtd
    Random string of length 6 is: ycfxbs
    Random string of length 4 is: dpla
    8,
    Random string of length 8 is: ijarubtd
    Random string of length 6 is: ycfxbs
    Random string of length 4 is: dpla
    9 và
    import random
    import string
    
    def get_random_string(length):
        # With combination of lower and upper case
        result_str = ''.join(random.choice(string.ascii_letters) for i in range(length))
        # print random string
        print(result_str)
    
    # string of length 8
    get_random_string(8)
    get_random_string(8)
    0 lại với nhau để tạo mật khẩu ngẫu nhiên và lặp lại bốn bước đầu tiên.

Ví dụ để tạo một chuỗi ngẫu nhiên có độ dài bất kỳ

import random
import string

def get_random_string(length):
    # choose from all lowercase letter
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Random string of length", length, "is:", result_str)

get_random_string(8)
get_random_string(6)
get_random_string(4)

Output::

Random string of length 8 is: ijarubtd
Random string of length 6 is: ycfxbs
Random string of length 4 is: dpla

  • Hàm lựa chọn ngẫu nhiên () được sử dụng để chọn một mục duy nhất từ ​​bất kỳ chuỗi nào và nó có thể lặp lại các ký tự.
  • Các chuỗi ngẫu nhiên ở trên chứa tất cả các chữ cái chữ thường. Nếu bạn chỉ muốn các chữ cái viết hoa, thì hãy sử dụng hằng số
    import random
    import string
    
    def get_random_string(length):
        # With combination of lower and upper case
        result_str = ''.join(random.choice(string.ascii_letters) for i in range(length))
        # print random string
        print(result_str)
    
    # string of length 8
    get_random_string(8)
    get_random_string(8)
    1 thay vào đó ở vị trí của
    Random string of length 8 is: ijarubtd
    Random string of length 6 is: ycfxbs
    Random string of length 4 is: dpla
    6.

Chuỗi ngẫu nhiên của chữ thường và chữ cái trên

Trong Python, để tạo ra một chuỗi ngẫu nhiên với sự kết hợp giữa các chữ cái chữ thường và chữ hoa, chúng ta cần sử dụng hằng số

import random
import string

def get_random_string(length):
    # With combination of lower and upper case
    result_str = ''.join(random.choice(string.ascii_letters) for i in range(length))
    # print random string
    print(result_str)

# string of length 8
get_random_string(8)
get_random_string(8)
3 làm nguồn. Hằng số này chứa tất cả các chữ cái chữ thường và chữ hoa.

Thí dụ

import random
import string

def get_random_string(length):
    # With combination of lower and upper case
    result_str = ''.join(random.choice(string.ascii_letters) for i in range(length))
    # print random string
    print(result_str)

# string of length 8
get_random_string(8)
get_random_string(8)

Output::

WxQqJQlD
NoCpqruK

Chuỗi ngẫu nhiên của các chữ cái cụ thể

Nếu bạn muốn tạo một chuỗi ngẫu nhiên từ một bộ ký tự cố định, vui lòng sử dụng ví dụ sau.

import random

# Random string of length 5
result_str = ''.join((random.choice('abcdxyzpqr') for i in range(5)))
print(result_str)
# Output ryxay

Chuỗi ngẫu nhiên mà không lặp lại các ký tự

Lưu ý: Phương thức

import random
import string

def get_random_string(length):
    # With combination of lower and upper case
    result_str = ''.join(random.choice(string.ascii_letters) for i in range(length))
    # print random string
    print(result_str)

# string of length 8
get_random_string(8)
get_random_string(8)
4 có thể lặp lại các ký tự. Nếu bạn không muốn các ký tự lặp lại trong một chuỗi kết quả, thì hãy sử dụng phương thức Random.sample ().: The
import random
import string

def get_random_string(length):
    # With combination of lower and upper case
    result_str = ''.join(random.choice(string.ascii_letters) for i in range(length))
    # print random string
    print(result_str)

# string of length 8
get_random_string(8)
get_random_string(8)
4 method can repeat characters. If you don’t want repeated characters in a resultant string, then use the random.sample() method.

import random
import string

for i in range(3):
    # get random string of length 6 without repeating letters
    result_str = ''.join(random.sample(string.ascii_lowercase, 8))
    print(result_str)

Output:

wxvdkbfl
ztondpef
voeduias

Cảnh báo: Như bạn có thể thấy trong đầu ra, tất cả các ký tự đều duy nhất, nhưng nó kém an toàn vì nó sẽ làm giảm xác suất kết hợp các chữ cái vì chúng tôi không cho phép các chữ cái và chữ số lặp đi lặp lại.: As you can see in the output, all characters are unique, but it is less secure because it will reduce the probability of combinations of letters because we are not allowing repetitive letters and digits.

Tạo mật khẩu ngẫu nhiên với các ký tự, chữ cái và chữ số đặc biệt

Mật khẩu chứa kết hợp các ký tự, chữ số và các ký hiệu đặc biệt được coi là mật khẩu mạnh.

Giả sử, bạn muốn tạo một mật khẩu ngẫu nhiên như: -

  • ab23cd#$
  • jk%m&l98
  • 87t@h*ki

Chúng ta có thể tạo một mật khẩu chuỗi ngẫu nhiên trong Python với các chữ cái, ký tự đặc biệt và các chữ số bằng hai cách sau.

  • Kết hợp ba hằng số sau và sử dụng chúng làm nguồn dữ liệu cho hàm
    import random
    import string
    
    def get_random_string(length):
        # With combination of lower and upper case
        result_str = ''.join(random.choice(string.ascii_letters) for i in range(length))
        # print random string
        print(result_str)
    
    # string of length 8
    get_random_string(8)
    get_random_string(8)
    5 để chọn các ký tự ngẫu nhiên từ nó.
    • Random string of length 8 is: ijarubtd
      Random string of length 6 is: ycfxbs
      Random string of length 4 is: dpla
      8: Bao gồm các chữ cái từ A-Z và A-Z
    • Random string of length 8 is: ijarubtd
      Random string of length 6 is: ycfxbs
      Random string of length 4 is: dpla
      9: Bao gồm các chữ số từ 1 đến 10
    • import random
      import string
      
      def get_random_string(length):
          # With combination of lower and upper case
          result_str = ''.join(random.choice(string.ascii_letters) for i in range(length))
          # print random string
          print(result_str)
      
      # string of length 8
      get_random_string(8)
      get_random_string(8)
      0: Để có được các biểu tượng đặc biệt
  • Sử dụng hàm
    import random
    import string
    
    def get_random_string(length):
        # With combination of lower and upper case
        result_str = ''.join(random.choice(string.ascii_letters) for i in range(length))
        # print random string
        print(result_str)
    
    # string of length 8
    get_random_string(8)
    get_random_string(8)
    9 Hằng số và
    import random
    import string
    
    def get_random_string(length):
        # With combination of lower and upper case
        result_str = ''.join(random.choice(string.ascii_letters) for i in range(length))
        # print random string
        print(result_str)
    
    # string of length 8
    get_random_string(8)
    get_random_string(8)
    4.
    import random
    import string
    
    def get_random_string(length):
        # With combination of lower and upper case
        result_str = ''.join(random.choice(string.ascii_letters) for i in range(length))
        # print random string
        print(result_str)
    
    # string of length 8
    get_random_string(8)
    get_random_string(8)
    9 chứa sự kết hợp của các chữ số, ascii_letters (chữ thường và chữ hoa), dấu câu và khoảng trắng.

Thí dụ

import random
import string

# get random password pf length 8 with letters, digits, and symbols
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for i in range(8))
print("Random password is:", password)

Output::

 import random
    letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
        
    print("Welcome to the Python Password Generator!")
    l= int(input("How many letters would you like in your password?\n")) 
    s = int(input(f"How many symbols would you like?\n"))
    n = int(input(f"How many numbers would you like?\n"))
        
    sequence = random.sample(letters,l)
    num      = random.sample(numbers,n)
    sym      = random.sample(symbols,s)
    sequence.extend(num)
    sequence.extend(sym)
         
    random.shuffle(sequence)
    password = ''.join([str(elem) for elem in sequence])#listToStr 
    print(password)
0

Sử dụng

import random
import string

def get_random_string(length):
    # With combination of lower and upper case
    result_str = ''.join(random.choice(string.ascii_letters) for i in range(length))
    # print random string
    print(result_str)

# string of length 8
get_random_string(8)
get_random_string(8)
9

 import random
    letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
        
    print("Welcome to the Python Password Generator!")
    l= int(input("How many letters would you like in your password?\n")) 
    s = int(input(f"How many symbols would you like?\n"))
    n = int(input(f"How many numbers would you like?\n"))
        
    sequence = random.sample(letters,l)
    num      = random.sample(numbers,n)
    sym      = random.sample(symbols,s)
    sequence.extend(num)
    sequence.extend(sym)
         
    random.shuffle(sequence)
    password = ''.join([str(elem) for elem in sequence])#listToStr 
    print(password)
1

Đầu ra

 import random
    letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
        
    print("Welcome to the Python Password Generator!")
    l= int(input("How many letters would you like in your password?\n")) 
    s = int(input(f"How many symbols would you like?\n"))
    n = int(input(f"How many numbers would you like?\n"))
        
    sequence = random.sample(letters,l)
    num      = random.sample(numbers,n)
    sym      = random.sample(symbols,s)
    sequence.extend(num)
    sequence.extend(sym)
         
    random.shuffle(sequence)
    password = ''.join([str(elem) for elem in sequence])#listToStr 
    print(password)
2

Mật khẩu ngẫu nhiên với số lượng chữ cái, chữ số và ký hiệu cố định

Đó là một trường hợp sử dụng rộng rãi rằng mật khẩu phải chứa một số số chữ số và ký hiệu đặc biệt.

Hãy cùng xem cách tạo ra một mật khẩu ngẫu nhiên chứa ít nhất một chữ cái viết thường, một chữ cái viết hoa, một chữ số và một biểu tượng đặc biệt.

Các bước: -: –

  • Đầu tiên, chọn số chữ cái chữ thường và chữ hoa ngẫu nhiên được chỉ định
  • Tiếp theo, chọn số chữ số ngẫu nhiên
  • Tiếp theo, chọn số lượng biểu tượng đặc biệt
  • Kết hợp cả chữ cái, chữ số và biểu tượng đặc biệt vào danh sách
  • Cuối cùng xáo trộn danh sách
  • Chuyển đổi danh sách trở lại chuỗi
 import random
    letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
        
    print("Welcome to the Python Password Generator!")
    l= int(input("How many letters would you like in your password?\n")) 
    s = int(input(f"How many symbols would you like?\n"))
    n = int(input(f"How many numbers would you like?\n"))
        
    sequence = random.sample(letters,l)
    num      = random.sample(numbers,n)
    sym      = random.sample(symbols,s)
    sequence.extend(num)
    sequence.extend(sym)
         
    random.shuffle(sequence)
    password = ''.join([str(elem) for elem in sequence])#listToStr 
    print(password)
3

Tạo một chuỗi và mật khẩu ngẫu nhiên an toàn

Trên hết, các ví dụ không được bảo mật bằng mật mã. Trình tạo ngẫu nhiên bảo mật bằng mã hóa tạo dữ liệu ngẫu nhiên bằng các phương pháp đồng bộ hóa để đảm bảo rằng không có hai quy trình nào có thể thu được cùng một dữ liệu.

Nếu bạn đang sản xuất mật khẩu hoặc chuỗi ngẫu nhiên cho một ứng dụng nhạy cảm với bảo mật, thì bạn phải sử dụng phương pháp này.

Nếu bạn đang sử dụng phiên bản Python nhỏ hơn 3.6, thì hãy sử dụng chức năng

WxQqJQlD
NoCpqruK
3 thay vì
import random
import string

def get_random_string(length):
    # With combination of lower and upper case
    result_str = ''.join(random.choice(string.ascii_letters) for i in range(length))
    # print random string
    print(result_str)

# string of length 8
get_random_string(8)
get_random_string(8)
5.

Nếu bạn đang sử dụng phiên bản Python cao hơn 3.6, bạn có thể sử dụng mô -đun Bí mật để tạo mật khẩu ngẫu nhiên an toàn.to generate a secure random password.

Sử dụng chức năng

WxQqJQlD
NoCpqruK
5 thay vì
import random
import string

def get_random_string(length):
    # With combination of lower and upper case
    result_str = ''.join(random.choice(string.ascii_letters) for i in range(length))
    # print random string
    print(result_str)

# string of length 8
get_random_string(8)
get_random_string(8)
5

 import random
    letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
        
    print("Welcome to the Python Password Generator!")
    l= int(input("How many letters would you like in your password?\n")) 
    s = int(input(f"How many symbols would you like?\n"))
    n = int(input(f"How many numbers would you like?\n"))
        
    sequence = random.sample(letters,l)
    num      = random.sample(numbers,n)
    sym      = random.sample(symbols,s)
    sequence.extend(num)
    sequence.extend(sym)
         
    random.shuffle(sequence)
    password = ''.join([str(elem) for elem in sequence])#listToStr 
    print(password)
4

Tạo một chuỗi chữ và chữ số ngẫu nhiên của các chữ cái và chữ số

Chúng tôi thường muốn tạo một chuỗi ngẫu nhiên chứa cả các chữ cái và chữ số như AB23CD, JKML98, 87thki. Trong những trường hợp như vậy, chúng tôi sử dụng hằng số

Random string of length 8 is: ijarubtd
Random string of length 6 is: ycfxbs
Random string of length 4 is: dpla
8 và
Random string of length 8 is: ijarubtd
Random string of length 6 is: ycfxbs
Random string of length 4 is: dpla
9 để có được sự kết hợp của các chữ cái và số trong chuỗi ngẫu nhiên của chúng tôi.

Bây giờ, hãy để Lừa xem để tạo một chuỗi ngẫu nhiên với sự kết hợp của một chữ cái từ A-Z, A-Z và các chữ số 0-9.

 import random
    letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
        
    print("Welcome to the Python Password Generator!")
    l= int(input("How many letters would you like in your password?\n")) 
    s = int(input(f"How many symbols would you like?\n"))
    n = int(input(f"How many numbers would you like?\n"))
        
    sequence = random.sample(letters,l)
    num      = random.sample(numbers,n)
    sym      = random.sample(symbols,s)
    sequence.extend(num)
    sequence.extend(sym)
         
    random.shuffle(sequence)
    password = ''.join([str(elem) for elem in sequence])#listToStr 
    print(password)
5

Chuỗi chữ và số ngẫu nhiên với số lượng chữ số và chữ số cố định

Ví dụ: tôi muốn tạo một chuỗi alpha-numeric ngẫu nhiên có chứa 5 chữ cái và 3 số.

Thí dụ

 import random
    letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
        
    print("Welcome to the Python Password Generator!")
    l= int(input("How many letters would you like in your password?\n")) 
    s = int(input(f"How many symbols would you like?\n"))
    n = int(input(f"How many numbers would you like?\n"))
        
    sequence = random.sample(letters,l)
    num      = random.sample(numbers,n)
    sym      = random.sample(symbols,s)
    sequence.extend(num)
    sequence.extend(sym)
         
    random.shuffle(sequence)
    password = ''.join([str(elem) for elem in sequence])#listToStr 
    print(password)
6

Output::

 import random
    letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
        
    print("Welcome to the Python Password Generator!")
    l= int(input("How many letters would you like in your password?\n")) 
    s = int(input(f"How many symbols would you like?\n"))
    n = int(input(f"How many numbers would you like?\n"))
        
    sequence = random.sample(letters,l)
    num      = random.sample(numbers,n)
    sym      = random.sample(symbols,s)
    sequence.extend(num)
    sequence.extend(sym)
         
    random.shuffle(sequence)
    password = ''.join([str(elem) for elem in sequence])#listToStr 
    print(password)
7

Sử dụng import random import string def get_random_string(length): # With combination of lower and upper case result_str = ''.join(random.choice(string.ascii_letters) for i in range(length)) # print random string print(result_str) # string of length 8 get_random_string(8) get_random_string(8)9

Đầu ra

Mật khẩu ngẫu nhiên với số lượng chữ cái, chữ số và ký hiệu cố định

 import random
    letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
        
    print("Welcome to the Python Password Generator!")
    l= int(input("How many letters would you like in your password?\n")) 
    s = int(input(f"How many symbols would you like?\n"))
    n = int(input(f"How many numbers would you like?\n"))
        
    sequence = random.sample(letters,l)
    num      = random.sample(numbers,n)
    sym      = random.sample(symbols,s)
    sequence.extend(num)
    sequence.extend(sym)
         
    random.shuffle(sequence)
    password = ''.join([str(elem) for elem in sequence])#listToStr 
    print(password)
8

Output::

 import random
    letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
        
    print("Welcome to the Python Password Generator!")
    l= int(input("How many letters would you like in your password?\n")) 
    s = int(input(f"How many symbols would you like?\n"))
    n = int(input(f"How many numbers would you like?\n"))
        
    sequence = random.sample(letters,l)
    num      = random.sample(numbers,n)
    sym      = random.sample(symbols,s)
    sequence.extend(num)
    sequence.extend(sym)
         
    random.shuffle(sequence)
    password = ''.join([str(elem) for elem in sequence])#listToStr 
    print(password)
9

Đó là một trường hợp sử dụng rộng rãi rằng mật khẩu phải chứa một số số chữ số và ký hiệu đặc biệt.

Hãy cùng xem cách tạo ra một mật khẩu ngẫu nhiên chứa ít nhất một chữ cái viết thường, một chữ cái viết hoa, một chữ số và một biểu tượng đặc biệt.

import random
import string

def get_random_string(length):
    # choose from all lowercase letter
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Random string of length", length, "is:", result_str)

get_random_string(8)
get_random_string(6)
get_random_string(4)
0

Các bước: -

Đầu tiên, chọn số chữ cái chữ thường và chữ hoa ngẫu nhiên được chỉ định

Các bước: -

  • import random
    
    # Random string of length 5
    result_str = ''.join((random.choice('abcdxyzpqr') for i in range(5)))
    print(result_str)
    # Output ryxay
    1.
  • Đầu tiên, chọn số chữ cái chữ thường và chữ hoa ngẫu nhiên được chỉ định

Tiếp theo, chọn số chữ số ngẫu nhiên

import random
import string

def get_random_string(length):
    # choose from all lowercase letter
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Random string of length", length, "is:", result_str)

get_random_string(8)
get_random_string(6)
get_random_string(4)
1

Tiếp theo, chọn số lượng biểu tượng đặc biệt

Kết hợp cả chữ cái, chữ số và biểu tượng đặc biệt vào danh sáchleaving a comment below.

Cuối cùng xáo trộn danh sáchrandom module exercise and quiz to have a better understanding of working with random data in Python.

Chuyển đổi danh sách trở lại chuỗi

Tạo một chuỗi và mật khẩu ngẫu nhiên an toànrandom alphanumeric string of length ten that must contain at least four digits. For example, the output can be anything like 1o32WzUS87, 1P56X9Vh87

Trên hết, các ví dụ không được bảo mật bằng mật mã. Trình tạo ngẫu nhiên bảo mật bằng mã hóa tạo dữ liệu ngẫu nhiên bằng các phương pháp đồng bộ hóa để đảm bảo rằng không có hai quy trình nào có thể thu được cùng một dữ liệu.

import random
import string

def get_random_string(length):
    # choose from all lowercase letter
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Random string of length", length, "is:", result_str)

get_random_string(8)
get_random_string(6)
get_random_string(4)
2

Làm thế nào để bạn tạo một ký tự ngẫu nhiên trong Python?

Mô-đun chuỗi có chức năng đặc biệt ASCII_Letters trả về một chuỗi chứa tất cả các bảng chữ cái từ A-Z và A-Z, tức là tất cả các bảng chữ cái chữ thường và chữ viết hoa.Sử dụng Random.choice (), chúng ta có thể chọn bất kỳ ký tự cụ thể nào từ chuỗi đó.Using random. choice() we can choose any of the particular characters from that string.

Làm thế nào để bạn tạo một chuỗi ngẫu nhiên từ một danh sách trong Python?

Sử dụng Random.RandRange () để chọn giá trị ngẫu nhiên từ danh sách.ngẫu nhiên.Phương thức randrange () được sử dụng để tạo một số ngẫu nhiên trong một phạm vi đã cho, chúng ta có thể chỉ định phạm vi là 0 đến độ dài của danh sách và nhận chỉ mục, sau đó là giá trị tương ứng. randrange() to select random value from a list. random. randrange() method is used to generate a random number in a given range, we can specify the range to be 0 to the length of the list, and get the index, and then the corresponding value.