簡體   English   中英

在python中使用正則表達式將制表符替換為空格

[英]Replace tab spaces with whitespace using regex in python

我被要求在 python 中使用正則表達式用空格替換制表符空格。 運行以下代碼:

text = "London is the capital of Great Britain"
x = re.sub(r"\t",r"\s", text)

我得到錯誤,它說:

    KeyError                                  Traceback (most recent call last)
~\anaconda3\lib\sre_parse.py in parse_template(source, state)
   1038                 try:
-> 1039                     this = chr(ESCAPES[this][1])
   1040                 except KeyError:

KeyError: '\\s'

During handling of the above exception, another exception occurred:

error                                     Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_600/989794690.py in <module>
      1 text = "London is the capital of Great Britain"
----> 2 x = re.sub(r"\t",r"\s", text)

~\anaconda3\lib\re.py in sub(pattern, repl, string, count, flags)
    208     a callable, it's passed the Match object and must return
    209     a replacement string to be used."""
--> 210     return _compile(pattern, flags).sub(repl, string, count)
    211 
    212 def subn(pattern, repl, string, count=0, flags=0):

~\anaconda3\lib\re.py in _subx(pattern, template)
    325 def _subx(pattern, template):
    326     # internal: Pattern.sub/subn implementation helper
--> 327     template = _compile_repl(template, pattern)
    328     if not template[0] and len(template[1]) == 1:
    329         # literal replacement

~\anaconda3\lib\re.py in _compile_repl(repl, pattern)
    316 def _compile_repl(repl, pattern):
    317     # internal: compile replacement pattern
--> 318     return sre_parse.parse_template(repl, pattern)
    319 
    320 def _expand(pattern, match, template):

~\anaconda3\lib\sre_parse.py in parse_template(source, state)
   1040                 except KeyError:
   1041                     if c in ASCIILETTERS:
-> 1042                         raise s.error('bad escape %s' % this, len(this))
   1043                 lappend(this)
   1044         else:

error: bad escape \s at position 0

誰能幫我解決這個問題? 我正在使用 python 3 和 jupyter 筆記本。

import re

text = "London\tis the\tcapital of Great\tBritain"

x = re.sub(r"\t",r" ", text)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM