Python:如何判断一个url是以http开头的?

本文介绍了如何在Python中使用startswith方法过滤出以http开头的URL。通过读取文本文件,结合startswith判断字符串是否以特定前缀开始,从而筛选出符合条件的URL。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python:如何判断一个url是以http开头的?

有一个文本,里面存放了很多的字符串,有的是以http开头的,有些不是,如何过滤出url呢?

Python:如何判断一个url是以http开头的?
比如一个文本test.txt,里面的内容为:

http://www.sogou.com
this is a url
this is http://www.sogou.com address

第一种方式是,判断包含:

#encoding: utf-8
 
with open("test.txt", "r") as f:
content = f.readlines()
for line in content:
 if "http" in line:
 print(line)

输出为:

http://www.sogou.com
this is http://www.sogou.com address

如果只获取以http开头的,那么:

#encoding: utf-8
import re
with open("test.txt", "r") as f:
content = f.readlines()
for line in content:
 r = re.match("http", line)
 if r != None:
 print(line)

输出为:

http://www.sogou.com

re.match, 从开头匹配字符串,如果匹配到返回匹配到的对象。没有匹配到返回None。

有没有更简单的方式呢?

#encoding: utf-8
with ope
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值