在问这个问题时,我意识到我对原始字符串知之甚少.对于那些自称是Django训练师的人来说,这很糟糕.
我知道编码是什么,而且我知道u''自从我得到什么是Unicode以来我们独自做了什么.
但到底r''做了什么呢?它会产生什么样的字符串?
And above all, what the heck does ur'' do?
Finally, is there any reliable way to go back from a Unicode string to a simple raw string?
Ah, and by the way, if your system and your text editor charset are set to UTF-8, does u'' actually do anything?
假设我想the blue dog and blue cat wore blue hats改为the gray dog and gray cat wore blue hats.
随着sed我能做到这一点,如下所示:
$ echo 'the blue dog and blue cat wore blue hats' | sed 's/blue \(dog\|cat\)/gray \1/g'
Run Code Online (Sandbox Code Playgroud)
如何在Python中进行类似的替换?我试过了:
>>> import re
>>> s = "the blue dog and blue cat wore blue hats"
>>> p = re.compile(r"blue (dog|cat)")
>>> p.sub('gray \1',s)
'the gray \x01 and gray \x01 wore blue hats'
Run Code Online (Sandbox Code Playgroud) 我有以下内容:
<text top="52" left="20" width="383" height="15" font="0"><b>test</b></text>
Run Code Online (Sandbox Code Playgroud)
我有以下内容:
fileText = re.sub("<b>(.*?)</b>", "\1", fileText, flags=re.DOTALL)
Run Code Online (Sandbox Code Playgroud)
其中fileText是我在上面发布的字符串.当我fileText运行正则表达式替换后打印出来时,我回来了
<text top="52" left="20" width="383" height="15" font="0"></text>
Run Code Online (Sandbox Code Playgroud)
而不是预期的
<text top="52" left="20" width="383" height="15" font="0">test</text>
Run Code Online (Sandbox Code Playgroud)
现在我对正则表达式相当熟练,我知道它应该可以工作,事实上我知道它匹配正确,因为我可以在groups搜索和打印出来的时候看到它groups但是我是python的新手而且我很困惑为什么它没有正确使用后向引用
如何在Python中使用正则表达式替换文件中的字符串,因为我想打开一个文件,我在其中替换其他字符串的字符串,我们需要使用Reg表达式(搜索和替换).任何人都可以帮助我吗?打开文件并将其与搜索和替换方法一起使用的一些示例