You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中使用lstrip('mailto:')提取邮箱时意外删除首字符i的问题

问题原因与解决办法

为什么lstrip("mailto:")会误删开头的'i'?

Python的lstrip()方法接收的参数是字符集合,不是固定的前缀字符串。也就是说,它会把字符串开头所有属于{'m','a','i','l','t','o',':'}的字符全部删掉,直到遇到不在这个集合里的字符为止。你的邮箱info@domain.com开头的'i'正好在这个集合里,所以被一起删掉了,导致结果变成nfo@domain.com。

正确的提取方法

方法1:用removeprefix()(Python 3.9及以上版本)

这是Python专门用来移除固定前缀的方法,只会匹配开头的完整前缀,不会误删后续字符:

mail_str = "mailto:info@domain.com"
email = mail_str.removeprefix("mailto:")
print(email)  # 输出: info@domain.com

方法2:字符串切片(兼容所有Python版本)

先判断字符串是否以mailto:开头,是的话直接截取前缀之后的部分:

mail_str = "mailto:info@domain.com"
prefix = "mailto:"
email = mail_str[len(prefix):] if mail_str.startswith(prefix) else mail_str
print(email)  # 输出: info@domain.com

内容的提问来源于stack exchange,提问作者Saeed Ahmad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 23:59:51