Search and replace operation

I have a list that has URL values ​​such as:

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

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

+6
source share
2 answers

Try the following:

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

If you want to make sure that only the las part is changed, and you know that all .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 extra context and avoid changes in the middle of the URL.

+8
source

Or if you want to do this on any file extension and make sure that nothing in the line is changed except the last.

 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) 

Exit:

 >>> 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' 
+4
source

Source: https://habr.com/ru/post/887267/


All Articles