Python 程序:生成隨機字符串

隨機是指可以以任何順序獲得的數據或信息的集合。python 中的random模塊用於生成隨機字符串。隨機字符串由數字、字符和標點符號序列組成,可以包含任何模式。random模塊包含兩種方法 random.choice() 和 secrets.choice() ,以生成安全字符串。讓我們了解如何使用 python 中的 random.choice()和 secrets.choice()方法生成隨機字符串。

**

使用 random.choice()

python 字符串中使用了 random.choice() 函數來生成可以以任何順序重複該字符串的字符和數字序列。

使用 random.choices()函數創建一個生成隨機字符串的程序。

Random_str.py


import string  
import random # define the random module
S = 10  # number of characters in the string.
# call random.choices() string module to find the string in Uppercase + numeric data.
ran = ''.join(random.choices(string.ascii_uppercase + string.digits, k = S))  
print("The randomly generated string is : " + str(ran)) # print the random data

輸出:

以下是random模塊中用來生成隨機字符串的方法。

| 方法 | 描述 |
| 字符串. ascii _ 字母 | 它返回一個隨機字符串,包含大寫和小寫字符。 |
| string ascii upper case | 這是一個隨機字符串方法,只返回大寫字符的字符串。 |
| string . ascii _ 小寫 | 這是一個隨機字符串方法,只返回小寫字符的字符串。 |
| 字符串數字 | 這是一個隨機字符串方法,返回帶有數字字符的字符串。 |
| 字符串.標點符號 | 這是一個隨機字符串方法,返回帶有標點符號的字符串。 |

生成大寫和小寫字母的隨機字符串

UprLwr.py


# write a program to generate the random string in upper and lower case letters.
import random
import string
def Upper_Lower_string(length): # define the function and pass the length as argument
    # Print the string in Lowercase
    result = ''.join((random.choice(string.ascii_lowercase) for x in range(length))) # run loop until the define length
    print(" Random string generated in Lowercase: ", result)

    # Print the string in Uppercase
    result1 = ''.join((random.choice(string.ascii_uppercase) for x in range(length))) # run the loop until the define length
    print(" Random string generated in Uppercase: ", result1)

Upper_Lower_string(10) # define the length

輸出:

指定字符的隨機字符串

special . py


# create a program to generate the random string of given letters.
import random
import string
def specific_string(length):
    sample_string = 'pqrstuvwxy' # define the specific string
    # define the condition for random string
    result = ''.join((random.choice(sample_string)) for x in range(length))
    print(" Randomly generated string is: ", result)

specific_string(8) # define the length
specific_string(10)

輸出:

注意:python 程序中使用了 random.choice()方法來重複相同的字符串。如果我們不想顯示重複的字符,我們應該使用 random.sample()函數。

生成隨機字符串,不重複相同的字符

撤回重複。py


# create a program to generate a string with or without repeating the characters.
import random
import string
print("Use of random.choice() method")
def specific_string(length):

    letters = string.ascii_lowercase # define the lower case string
     # define the condition for random.choice() method
    result = ''.join((random.choice(letters)) for x in range(length))
    print(" Random generated string with repetition: ", result)

specific_string(8) # define the length
specific_string(10)

print("") # print the space
print("Use of random.sample() method")
def WithoutRepeat(length):
    letters = string.ascii_lowercase # define the specific string
    # define the condition for random.sample() method
    result1 = ''.join((random.sample(letters, length))) 
    print(" Random generated string without repetition: ", result1)

WithoutRepeat(8) # define the length
WithoutRepeat(10) 

輸出:

正如我們在上面的輸出中所看到的,random.sample()方法返回一個字符串,其中所有字符都是唯一且不重複的。而 random.choice()方法返回可能包含重複字符的字符串。因此,我們可以說,如果我們想要生成一個唯一的隨機字符串,請使用 random.sample ()方法。

生成由固定字母和數字組成的隨機字母數字字符串

例如,假設我們想要一個隨機生成的包含五個字母和四個數字的字母數字字符串。我們需要在函數中定義這些參數。

讓我們編寫一個程序來生成一個包含固定數量的字母和數字的字母數字字符串。

固定環. py


import random
import string
def random_string(letter_count, digit_count):
    str1 = ''.join((random.choice(string.ascii_letters) for x in range(letter_count)))
    str1 += ''.join((random.choice(string.digits) for x in range(digit_count)))

    sam_list = list(str1) # it converts the string to list.
    random.shuffle(sam_list) # It uses a random.shuffle() function to shuffle the string.
    final_string = ''.join(sam_list)
    return final_string

# define the length of the letter is eight and digits is four
print("Generated random string of first string is:", random_string(8, 4))

# define the length of the letter is seven and digits is five
print("Generated random string of second string is:", random_string(7, 5))

輸出:

使用秘密。選擇()

secrets.choice()方法用於生成比 random.choice()更安全的隨機字符串。它是一個加密隨機字符串生成器,確保沒有兩個進程可以使用 secrets.choice()方法同時獲得相同的結果。

讓我們編寫一個程序,使用 secrets.choice 方法打印一個安全的隨機字符串。

Secret_str.py


import random 
import string
import secrets # import package
num = 10 # define the length of the string
# define the secrets.choice() method and pass the string.ascii_letters + string.digits as an parameters.
res = ''.join(secrets.choice(string.ascii_letters + string.digits) for x in range(num))

# print the Secure string 
print("Secure random string is :"+ str(res))

輸出:

使用random模塊的不同方法生成安全的隨機字符串。

讓我們編寫一個程序,使用不同的方法打印安全的隨機字符串。

Secret.py


# write a program to display the different random string method using the secrets.choice().
# imports necessary packages
import random 
import string
import secrets
num = 10 # define the length of the string
# define the secrets.choice() method and pass the string.ascii_letters + string.digits as an parameters.
res = ''.join(secrets.choice(string.ascii_letters + string.digits) for x in range(num))
# Print the Secure string with the combination of ascii letters and digits
print("Secure random string is :"+ str(res))

res = ''.join(secrets.choice(string.ascii_letters) for x in range(num))
# Print the Secure string with the combination of ascii letters 
print("Secure random string is :"+ str(res))

res = ''.join(secrets.choice(string.ascii_uppercase) for x in range(num))
# Print the Secure string in Uppercase
print("Secure random string is :"+ str(res))

res = ''.join(secrets.choice(string.ascii_lowercase) for x in range(num))
# Print the Secure string in Lowercase
print("Secure random string is :"+ str(res))

res = ''.join(secrets.choice(string.ascii_letters + string.punctuation) for x in range(num))
# Print the Secure string with the combination of letters and punctuation
print("Secure random string is :"+ str(res))

res = ''.join(secrets.choice(string.digits) for x in range(num))
# Print the Secure string using string.digits
print("Secure random string is :"+ str(res))

res = ''.join(secrets.choice(string.ascii_letters + string.digits + string.punctuation) for x in range(num))
# Print the Secure string with the combonation of letters, digits and punctuation 
print("Secure random string is :"+ str(res))

輸出:


原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/236447.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-12 12:00
下一篇 2024-12-12 12:00

相關推薦

  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智能、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29

發表回復

登錄後才能評論