繁体   English   中英

Python re.sub问题

[英]Python re.sub issue

我正在尝试使用re.sub清理字符串以将文本转换为时间。 我的初始字符串是"Durée : 1h30" ,我想删除"Durée : "并获得以下输出: "1h30" 但是,使用我当前的代码,输出是以下字符串列表: ["D", "u", "r", "é", "e", " ", ":", " ", "1", "h", "3", "0"]

for href in response.xpath("//div[@class='item']/a[@class='roll-2']//@href"):
        url = "https://www.louvre.fr" + href.extract()
        yield scrapy.Request(url, callback=self.parse_dir_contents)

lenght = response.xpath("//tbody/tr/td/text()").extract()[1]  #lenght = "Durée : 1h30"

item['lenght'] = [re.sub("Durée : ", "", le) for le in lenght]

字符串在Python中是可迭代的,并且您要遍历列表re.sub中的每个字符,并分别在这些字符中运行re.sub

另外,您在这里不需要正则表达式。 使用str.replace

item['length'] = [length.replace('Durée : ', '')]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM