c# - 用小写字母进行 Python URL 编码?

标签 c# python asp.net url encoding

使用 urllib.parse.quote 时编码全部大写。我的代理服务器是用 C# 编写的,除了要小写的编码。

例如,<编码(UTF-8)为%3C .但是,C# 的 WebUtility.UrlDecode(request.RawUrl)除所有小写字母外:%3c .结果是两个系统无法相互通信。

C# ASP.NET 确实有另一个函数可以处理大写编码。此功能不再存在。 (已退休)Link to used C# function

import urllib
my_text="?address=This is an Address!&name=This is a test of it all!<.>"
my_url=urllib.parse.quote(my_text)
my_url

我希望在 python 端用小写字母对 URL 进行编码。关于如何实现这一目标的任何想法?

另一种可能的解决方案是在 C# 端用大写字母解码 URL,但似乎没有用于此的函数。 :(

最佳答案

I'm hoping to encode the URL on the python side with lowercase letters. Any idea on how to make this happen?

我们有正则表达式,它是一种强大的武器。试试这个:

import re
import urllib.parse  # I'm curious that you just imported `urllib`.


my_text = "?address=This is an Address!&name=This is a test of it all!<.>"
my_url = re.sub(r'%[0-9A-Z]{2}',                             # pattern
                lambda matchobj: matchobj.group(0).lower(),  # function used to replace matched string
                urllib.parse.quote(my_text))                 # input string
my_url

输出是:

%3faddress%3dThis%20is%20an%20Address%21%26name%3dThis%20is%20a%20test%20of%20it%20all%21%3c.%3e

与原来的对比:

%3Faddress%3DThis%20is%20an%20Address%21%26name%3DThis%20is%20a%20test%20of%20it%20all%21%3C.%3E

这将满足您的要求。


如果要这样处理多个URL,最好使用regular expression object :

import re
import urllib.parse


my_re = re.compile(r'%[0-9A-Z]{2}')  # pattern

my_text = "?address=This is an Address!&name=This is a test of it all!<.>"
my_url = my_re.sub(lambda matchobj: matchobj.group(0).lower(),  # function used to replace matched string
                   urllib.parse.quote(my_text))                 # input string
my_url

文档:

关于c# - 用小写字母进行 Python URL 编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56277719/

相关文章:

c# - 如何从字符串为 Lambda 表达式动态创建方法

python - Django 查询集 : filter by the value of another field

python - 如何将 `cv2.imwrite()` 输出到标准输出?

c# - 检测是否在 ASP.Net 中的移动浏览器上启用了 JavaScript

c# - ASP.NET 用户消息传递/聊天 - 现成的解决方案?

c# - WPF 自定义控件/控件模板

c# - 使用 Azure、Https 和远程 HTTP 调用组合删除 session

c# - 使用 CSharpCodeProvider 时出现运行时错误程序集 'System.Runtime'

python - 删除超过特定深度的所有子标签

c# - 存储库模式逐步解释