首页 > 解决方案 > python字符串在某个字符之前更改字符串中的字符

问题描述

我有这个 url,想将 px 值从 160 更改为 500。如果不知道字符的索引,我该怎么做?我用替换功能试过了

https://someurl.com//img_cache/381a58s7943437_037_160px.jpg?old

我想要的是:

https://someurl.com//img_cache/381a58s7943437_037_500px.jpg?old

标签: pythonstring

解决方案


此处的正则表达式\d+(?=px)查找前面的数字,px然后将它们替换为您在参数中输入的任何内容new_res

import re

string = "https://someurl.com//img_cache/381a58s7943437_037_160px.jpg?old"
new_res = "500"
out = re.sub("\d+(?=px)", new_res, string)

print(out)

输出:

https://someurl.com//img_cache/381a58s7943437_037_500px.jpg?old

推荐阅读