可以在函数内部使用python re占位符吗?如果是,怎么办? [或更笼统地讲-串起一串线]

是否可以在python子函数中使用\ 1匹配项?例如ord(“ \ 1”)我注意到这不起作用:

$ python3.7 -c 'import re; a="fred<was>=he re, n=-3.13e-05;\n"; print(re.sub(r"([^'0'-'9''A'-'Z''a'-'z'\.\-\_])","%"+hex(ord("\\1")), a)) ' 
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found

而且“长度2”非常意外,因为如您所见,它不是2:-

$ python3.7 -c 'import re; a="fred<was>=he re, n=-3.13e-05;\n"; print(re.sub(r"([^'0'-'9''A'-'Z''a'-'z'\.\-\_])","(\\1)", a)) '             
fred(<)was(>)(=)he( )re(,)( )n(=)-3.13e-05(;)(
)

研究其中的内容表明函数正在接收文字'\ 1'而不是替代内容(0x5C为“ \”,0x31为“ 1”):

$ python3.7 -c 'import re; a="fred<was>=he re, n=-3.13e-05;\n"; print(re.sub(r"([^'0'-'9''A'-'Z''a'-'z'\.\-\_])","%"+hex(ord("\\1"[0])), a)) ' 
fred%0x5cwas%0x5c%0x5che%0x5cre%0x5c%0x5cn%0x5c-3.13e-05%0x5c%0x5c
$ python3.7 -c 'import re; a="fred<was>=he re, n=-3.13e-05;\n"; print(re.sub(r"([^'0'-'9''A'-'Z''a'-'z'\.\-\_])","%"+hex(ord("\\1"[1])), a)) ' 
fred%0x31was%0x31%0x31he%0x31re%0x31%0x31n%0x31-3.13e-05%0x31%0x31

因此,我的问题是...是否可以使用技巧或替代方法将实际的占位符放入ord()中?

...

或者:我处于无法依赖urllib的环境中。

底线-我正在尝试重现这样的内容:-

$ perl -e '$a="fred<was>=he re, n=-3.13e+05;\n"; $a=~s/([^A-Za-z0-9\._-])/sprintf("%%%02X", ord($1))/seg; print "$a\n"' 
fred%3Cwas%3E%3Dhe%20re%2C%20n%3D-3.13e%2B05%3B%0A

顺便说一句,请原谅-在Google几个小时后还没有给出答案,我是python的新手,像“ \ 1”这样的搜索字词就很棘手...