【问题标题】:Using .find(" ") method without cutting last character if the substring is at the very end如果子字符串位于末尾,则使用 .find(" ") 方法而不剪切最后一个字符
【发布时间】:2017-10-13 11:23:57
【问题描述】:

我正在尝试找到一个子字符串,它基本上是指向任何网站的链接。这个想法是,如果用户发布了一些东西,链接将被提取并分配给一个名为 web_link 的变量。我当前的代码如下:

post = ("You should watch this video https://www.example.com if you have free time!")
web_link = post[post.find("http" or "www"):post.find(" ", post.find("http" or "www"))]

如果链接后面有空格键,则代码可以完美运行,但是,如果帖子内的链接位于最后。例如:

post = ("You should definitely watch this video https://www.example.com")

然后post.find(" ") 找不到空格键/空格并返回-1 导致web_link "https://www.example.co"

如果可能的话,我正在尝试找到一个不涉及 if 语句的解决方案。

【问题讨论】:

  • 旁注:if 不是函数。
  • 你应该使用正则表达式,否则你的函数不会很健壮......一个简单的“python从字符串中提取url”谷歌搜索会解决你的问题

标签: python python-3.x find


【解决方案1】:

使用正则表达式。我对解决方案here做了一点改动。

import re

def func(post):
    return re.search("[(http|ftp|https)://]*([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?", post).group(0)

print(func("You should watch this video www.example.com if you have free time!"))
print(func("You should watch this video https://www.example.com"))

输出:

www.example.com
https://www.example.com

但我应该说,使用 "if" 更简单明了:

def func(post):
    start = post.find("http" or "www")
    finish = post.find(" ", start)
    return post[start:] if finish == -1 else post[start:finish]

【讨论】:

    【解决方案2】:

    这不起作用的原因是,如果未找到字符串并返回 -1,切片命令会将其解释为“字符串的其余部分 -1 字符从末尾开始”。

    正如 ifma 指出的那样,实现这一目标的最佳方法是使用正则表达式。比如:

    re.search("(https?://|www[^\s]+)", post).group(0)
    

    【讨论】:

    • 这不包括以“www”开头的网络链接。实际上,如果你使用没有“https”的字符串,你会得到这个错误:AttributeError: 'NoneType' object has no attribute 'group'
    • 是的,很公平。更新以考虑到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    相关资源
    最近更新 更多