Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search and replace operation

Tags:

python

replace

I have a list which has URL values like:

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

How can I change the _s in the end to _m for all occurrences?

like image 393
prateek Avatar asked May 04 '11 10:05

prateek


2 Answers

Try this:

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

If you want to be sure that only the las part is changed and you know all are .jpg files you can use:

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

To give some more context and avoid changes on the middle of the url.

like image 195
pconcepcion Avatar answered Oct 09 '22 10:10

pconcepcion


Or if you want to be able to do this on any file extension and make sure nothing in the string is altered except for the last part.

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)

Output:

>>> 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'
like image 39
rzetterberg Avatar answered Oct 09 '22 10:10

rzetterberg