搜索和替换操作

时间:2011-05-04 10:48:04

标签: python replace

我有一个列表,其URL值如下:

http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.jpg

如何针对所有事件将_s最终更改为_m

2 个答案:

答案 0 :(得分:8)

试试这个:

str = "http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.jpg"
str = str.replace("_s","_m")

如果您想确保只更改了las部分并且您知道所有.jpg个文件都可以使用:

str = "http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.jpg"
str = str.replace("_s.jpg","_m.jpg")

提供更多上下文并避免在网址中间进行更改。

答案 1 :(得分:4)

或者,如果您希望能够在任何文件扩展名上执行此操作,并确保字符串中的任何内容都不会被更改,除了最后一部分。

import re

str = "http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.jpg"
re.sub("(.*)_s(\.[a-z0-9]{1,4})$", r"\1_m\2", str)
str = "http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.png"
re.sub("(.*)_s(\.[a-z0-9]{1,4})$", r"\1_m\2", str)
str = "http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.gif"
re.sub("(.*)_s(\.[a-z0-9]{1,4})$", r"\1_m\2", str)
str = "http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.zip"
re.sub("(.*)_s(\.[a-z0-9]{1,4})$", r"\1_m\2", str)

输出:

>>> str = "http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.jpg"
>>> re.sub("(.*)_s(\.[a-z0-9]{1,4})$", r"\1_m\2", str)
'http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_m.jpg'

>>> str = "http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.png"
>>> re.sub("(.*)_s(\.[a-z0-9]{1,4})$", r"\1_m\2", str)
'http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_m.png'

>>> str = "http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.gif"
>>> re.sub("(.*)_s(\.[a-z0-9]{1,4})$", r"\1_m\2", str)
'http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_m.gif'

>>> str = "http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.zip"
>>> re.sub("(.*)_s(\.[a-z0-9]{1,4})$", r"\1_m\2", str)
'http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_m.zip'
相关问题