簡體   English   中英

從 Python 字符串中刪除轉義序列

[英]Remove Escape Sequence from Python String

我正在開發一個簡單的函數,它為新用戶生成隨機密碼並通過電子郵件發送給他們。 這是我的代碼的相關部分:

import string
import random

def create_temporary_password():
    characters = string.ascii_letters + string.punctuation + string.digits
    return "".join(random.choice(characters) for _ in range(RANDOM_PW_LENGTH))

def main():
    temp_password = create_temporary_password()
    my_send_email_function(
        to='example@123.com',
        subject='Your Password',
        body="Your temporary password is {temp_password}"
    )

(除此之外還有很多,我已經取出了非必需品)

有沒有一種簡單的方法可以確保 temp_password 不會偶然以 \n 或類似的轉義序列結束,這可能會破壞通過電子郵件發送密碼的格式?

這可以通過使用string.replace方法來實現:

password = "".join(random.choice(characters) for _ in range(RANDOM_PW_LENGTH))
return password.replace('\n', '')

這將替換密碼中所有出現的“\n”。

如果您想從字符串中刪除其他特殊字符,您可以創建一個包含要刪除的列表,然后循環上面的代碼一次選擇一個特殊字符,或者更簡單,您可以刪除所有出現的'\' 來自字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM