python字符串将字符串中的字符更改为特定字符之前的字符

python字符串将字符串中的字符更改为特定字符之前的字符,python,string,Python,String,我有这个url,想把px值从160改为500。我如何在不知道字符索引的情况下执行此操作?我试过用替换函数 https://someurl.com//img_cache/381a58s7943437_037_160px.jpg?old 我想要的是: https://someurl.com//img_cache/381a58s7943437_037_500px.jpg?old 这里的regexp\d+(?=px)查找px前面的数字,然后用参数new\u res中的任何内容替换它们 import

我有这个url,想把px值从160改为500。我如何在不知道字符索引的情况下执行此操作?我试过用替换函数

https://someurl.com//img_cache/381a58s7943437_037_160px.jpg?old
我想要的是:

https://someurl.com//img_cache/381a58s7943437_037_500px.jpg?old
这里的regexp
\d+(?=px)
查找
px
前面的数字,然后用参数
new\u 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
https://someurl.com//img_cache/381a58s7943437_037_540px.jpg?old
>>> 

您可以使用一个正则表达式模式来查找一个或多个数字,并使用一个肯定的前瞻性断言紧跟其后的是子字符串px.jpg:

输出:

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

到目前为止你试过什么?也许可以尝试使用正则表达式捕获前面的组、数字和后面的组,然后用新值构造一个字符串?这将在
px
jpg
@LaytonGB之间剪切
。我修好了。
https://someurl.com//img_cache/381a58s7943437_037_540px.jpg?old
>>>