Search and replace operation

2019-02-13 16:19发布

问题:

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?

回答1:

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.



回答2:

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'