[英]How can I use regular expression or any other method to sub a specific pattern of a string (python 2.7)?
所以我拥有的字符串网址是'http://helloworld.net/b/c/3?nw=174057&csid=fire.clan.com/gram/&din=&rand=52710&w=400&h=112'
。 这是在python 2.7中。
现在,网址中的参数rand不断变化,并且始终为5个数字,因此可以为rand=12345
或99999
等
现在我想在这种情况下( 'rand=52710'
)更改为'sub'
或仅仅是''
我已经通过使用https://developers.google.com/edu/python/regular-expressions
进行了尝试,但没有提出可靠的解决方案
任何帮助,将不胜感激谢谢。
使用正则表达式 。
例如:
import re
u = 'http://helloworld.net/b/c/3?nw=174057&csid=fire.clan.com/gram/&din=&rand=52710&w=400&h=112'
print re.sub("rand\=\d+", "SUB", u)
输出:
http://helloworld.net/b/c/3?nw=174057&csid=fire.clan.com/gram/&din=&SUB&w=400&h=112
如果没有正则表达式,则假设您的声明“ 现在URL中的参数rand一直在变化,并且始终为5个数字的长度,因此可以是rand = 12345或99999 ”成立:
url = "http://helloworld.net/b/c/3?csid=fire.clan.com/gram/&din=&rand=52710&w=400&h=112"
index = url.rfind("rand=")
if index != -1:
url = url[:index] + url[index+11:] # add 'sub' between url parts if you want it
# http://helloworld.net/b/c/3?csid=fire.clan.com/gram/&din=&w=400&h=112
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.