如何在字符串搜索中使用“find”来定位搜索结果左侧的起始位置

2024-09-25 00:35:09 发布

您现在位置:Python中文网/ 问答频道 /正文

请原谅我可能张贴了最愚蠢的问题,但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)

Tags: 代码dataaddress电子邮件地址结尾find事情
2条回答

您可以将字符串按空格分开,然后为每个单词检查是否有@字符串。如果是这样的话,那么您就可以用@字符串来拆分单词,从而得到左右两侧的部分

data = "From random-text myemail@gmail.com Sat 21:19"
for text in data.split():
    if "@" in text:
        left, right = text.split('@')
        print(f'The email starts with "{left}" and is in the domain "{right}"')

输出

The email starts with "myemail" and is in the domain "gmail.com"

更新

如果你真的想用索引位置来做这件事,然后找到。那么您已经知道如何找到@的位置,并且知道如何通过指定起始索引来搜索@之后的第一个空间

find的文档指定它查找最低的索引。但是,我们可以使用rfind来查找最高的索引,即字符串中的最后一个事件

string.find(s, sub[, start[, end]]) Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices.

string.rfind(s, sub[, start[, end]]) Like find() but find the highest index

所以使用rfind我们可以找到字符串中最后一个空格实例。如果我们传递0作为开始(因此从开始处开始),然后传递@的索引作为结束,那么它将找到字符串开始和@符号之间最后一个空格字符的索引。然后我们要加1,因为我们不需要空间的索引,而是后面的索引

data = "From random-text myemail@gmail.com Sat 21:19"
#get the index of the @
at_index = data.find('@') 

# get the first index of space starting after @
right_index = data.find(' ', at_index) 

# get the last index of space starting from start but not exceeding index of @
left_index = data.rfind(' ', 0, at_index) + 1 

print(data[left_index:right_index])

输出

myemail@gmail.com
data = "From random-text myemail@gmail.com Sat 21:19"
data_list = data.split(' ')
for word in data_list:
    if '@' in word:
        print(word)

稍后,您可以通过使用“@”符号拆分此循环结果来提取电子邮件域和名称

相关问题 更多 >