从Python字符串中删除逃生序列

发布于 2025-01-29 20:10:48 字数 693 浏览 4 评论 0原文

我正在研究一个简单的功能,该功能为新用户生成随机密码,并通过电子邮件将其发送给他们。这是我的代码的相关部分:(

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='[email protected]',
        subject='Your Password',
        body="Your temporary password is {temp_password}"
    )

除此之外,我已经取出了不必要的)

。通过电子邮件发送时,哪个可以搞砸密码的格式?

I'm working on a simple function that generates a random password for a new user and sends it to them via email. Here's the relevant part of my code:

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='[email protected]',
        subject='Your Password',
        body="Your temporary password is {temp_password}"
    )

(There's a lot more to it than this, I've taken out the nonessentials)

Is there an easy way to ensure that temp_password doesn't by chance end up with \n or a similar escape sequence which could screw up the way the password is formatted when sent via email?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

挥剑断情 2025-02-05 20:10:48

这可以通过使用string.replace方法来实现:

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

这将替换密码中所有“ \ n”的出现。

如果您想从字符串中删除其他特殊字符,则可以使用要删除的列表创建一个列表,并循环上面的代码一次选择一个特殊的char,甚至更容易,您只需删除所有出现'\'从字符串中。

This can be achieved by using string.replace method:

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

This will replace all occurrences of '\n' in the password.

If you'd like to remove other special chars from the string, you could create a list with the ones you wish to remove, and loop the code above selecting one special char at once, or even easier, you could just remove all occurrences of '\' from the string.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文