请原谅我可能张贴了最愚蠢的问题,但Python新手在这里。我在regex的章节中,从文件中提取电子邮件地址似乎很容易。问题是,我还不知道如何使用“普通”代码来实现这一点。我可以使用找到“@”的位置,然后通过找到“@”后面的下一个空格找到电子邮件地址的结尾。但是如何将搜索移到“@”的“左侧”?没有发现
这可能是最简单的事情,但我已经搜索了这么多的网站,现在我放弃了,并在这里创建了一个帐户。我想如果我是负数的话,我可能会向左移动,但是错了。如果有人能帮我打开灯泡,我将非常感激。非常感谢
示例:
data = "From random-text myemail@gmail.com Sat 21:19"
atpos = data.find("@")
end = data.find(" ",atpos)
start = data.find(" ",**???**,**???**)
address = data[start:end]
print(address)
您可以将字符串按空格分开,然后为每个单词检查是否有
@
字符串。如果是这样的话,那么您就可以用@
字符串来拆分单词,从而得到左右两侧的部分输出
更新
如果你真的想用索引位置来做这件事,然后找到。那么您已经知道如何找到
@
的位置,并且知道如何通过指定起始索引来搜索@
之后的第一个空间find的文档指定它查找最低的索引。但是,我们可以使用
rfind
来查找最高的索引,即字符串中的最后一个事件所以使用rfind我们可以找到字符串中最后一个空格实例。如果我们传递0作为开始(因此从开始处开始),然后传递
@
的索引作为结束,那么它将找到字符串开始和@
符号之间最后一个空格字符的索引。然后我们要加1,因为我们不需要空间的索引,而是后面的索引输出
稍后,您可以通过使用“@”符号拆分此循环结果来提取电子邮件域和名称
相关问题 更多 >
编程相关推荐