python3 re.sub 解决missing < at position 54

本文探讨了在使用Python的re.sub函数时,如果替换字符串repl包含特殊字符,Python仅处理 和 的情况。针对g导致的错误,提供了三种解决方法:1) 使用fr字符串;2) 替换g为g;3) 使用repr转换repl。这些技巧对于避免正则表达式中的解析错误至关重要。

re.sub中如果repl含有特殊字符,则Python只处理了\r,\n,其他字符未做处理。如果含有\g则会报错missing < at position 54

解法办法
1,在某些版本中,可以使用fr"{repl}",我本地win10、python3.6上可以这样处理
2,使用replace,把\g换成\g,其他字符类似
3,repl=repr(repl)

error Traceback (most recent call last) Cell In[1], line 1 ----> 1 get_ipython().run_line_magic(&#39;conda&#39;, &#39;install -c conda-forge gdal numpy scipy matplotlib jupyter&#39;) File D:\miniconda3\envs\jupyter_env\lib\site-packages\IPython\core\interactiveshell.py:2456, in InteractiveShell.run_line_magic(self, magic_name, line, _stack_depth) 2454 kwargs[&#39;local_ns&#39;] = self.get_local_scope(stack_depth) 2455 with self.builtin_trap: -> 2456 result = fn(*args, **kwargs) 2458 # The code below prevents the output from being displayed 2459 # when using magics with decorator @output_can_be_silenced 2460 # when the last Python token in the expression is a &#39;;&#39;. 2461 if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False): File D:\miniconda3\envs\jupyter_env\lib\site-packages\IPython\core\magics\packaging.py:30, in is_conda_environment.<locals>.wrapper(*args, **kwargs) 25 if not Path(sys.prefix, "conda-meta", "history").exists(): 26 raise ValueError( 27 "The python kernel does not appear to be a conda environment. " 28 "Please use ``%pip install`` instead." 29 ) ---> 30 return func(*args, **kwargs) File D:\miniconda3\envs\jupyter_env\lib\site-packages\IPython\core\magics\packaging.py:128, in PackagingMagics.conda(self, line) 120 @line_magic 121 @is_conda_environment 122 def conda(self, line): 123 """Run the conda package manager within the current kernel. 124 125 Usage: 126 %conda install [pkgs] 127 """ --> 128 conda = _get_conda_like_executable("conda") 129 self._run_command(conda, line) File D:\miniconda3\envs\jupyter_env\lib\site-packages\IPython\core\magics\packaging.py:53, in _get_conda_like_executable(command) 50 # Otherwise, attempt to extract the executable from conda history. 51 # This applies in any conda environment. 52 history = Path(sys.prefix, "conda-meta", "history").read_text(encoding="utf-8") ---> 53 match = re.search( 54 rf"^#\s*cmd:\s*(?P<command>.*{executable})\s[create|install]", 55 history, 56 flags=re.MULTILINE, 57 ) 58 if match: 59 return match.groupdict()["command"] File D:\miniconda3\envs\jupyter_env\lib\re.py:201, in search(pattern, string, flags) 198 def search(pattern, string, flags=0): 199 """Scan through string looking for a match to the pattern, returning 200 a Match object, or None if no match was found.""" --> 201 return _compile(pattern, flags).search(string) File D:\miniconda3\envs\jupyter_env\lib\re.py:304, in _compile(pattern, flags) 302 if not sre_compile.isstring(pattern): 303 raise TypeError("first argument must be string or compiled pattern") --> 304 p = sre_compile.compile(pattern, flags) 305 if not (flags & DEBUG): 306 if len(_cache) >= _MAXCACHE: 307 # Drop the oldest item File D:\miniconda3\envs\jupyter_env\lib\sre_compile.py:788, in compile(p, flags) 786 if isstring(p): 787 pattern = p --> 788 p = sre_parse.parse(p, flags) 789 else: 790 pattern = None File D:\miniconda3\envs\jupyter_env\lib\sre_parse.py:955, in parse(str, flags, state) 952 state.str = str 954 try: --> 955 p = _parse_sub(source, state, flags & SRE_FLAG_VERBOSE, 0) 956 except Verbose: 957 # the VERBOSE flag was switched on inside the pattern. to be 958 # on the safe side, we&#39;ll parse the whole thing again... 959 state = State() File D:\miniconda3\envs\jupyter_env\lib\sre_parse.py:444, in _parse_sub(source, state, verbose, nested) 442 start = source.tell() 443 while True: --> 444 itemsappend(_parse(source, state, verbose, nested + 1, 445 not nested and not items)) 446 if not sourcematch("|"): 447 break File D:\miniconda3\envs\jupyter_env\lib\sre_parse.py:841, in _parse(source, state, verbose, nested, first) 838 raise source.error(err.msg, len(name) + 1) from None 839 sub_verbose = ((verbose or (add_flags & SRE_FLAG_VERBOSE)) and 840 not (del_flags & SRE_FLAG_VERBOSE)) --> 841 p = _parse_sub(source, state, sub_verbose, nested + 1) 842 if not source.match(")"): 843 raise source.error("missing ), unterminated subpattern", 844 source.tell() - start) File D:\miniconda3\envs\jupyter_env\lib\sre_parse.py:444, in _parse_sub(source, state, verbose, nested) 442 start = source.tell() 443 while True: --> 444 itemsappend(_parse(source, state, verbose, nested + 1, 445 not nested and not items)) 446 if not sourcematch("|"): 447 break File D:\miniconda3\envs\jupyter_env\lib\sre_parse.py:526, in _parse(source, state, verbose, nested, first) 523 continue 525 if this[0] == "\\": --> 526 code = _escape(source, this, state) 527 subpatternappend(code) 529 elif this not in SPECIAL_CHARS: File D:\miniconda3\envs\jupyter_env\lib\sre_parse.py:427, in _escape(source, escape, state) 425 if len(escape) == 2: 426 if c in ASCIILETTERS: --> 427 raise source.error("bad escape %s" % escape, len(escape)) 428 return LITERAL, ord(escape[1]) 429 except ValueError: error: bad escape \m at position 28出什么错了,怎么解决
最新发布
10-20
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值