从Python字符串中删除逃生序列
我正在研究一个简单的功能,该功能为新用户生成随机密码,并通过电子邮件将其发送给他们。这是我的代码的相关部分:(
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可以通过使用
string.replace
方法来实现:这将替换密码中所有“ \ n”的出现。
如果您想从字符串中删除其他特殊字符,则可以使用要删除的列表创建一个列表,并循环上面的代码一次选择一个特殊的char,甚至更容易,您只需删除所有出现'\'从字符串中。
This can be achieved by using
string.replace
method: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.