我有一个输入,我需要用and替换&&

Note : &&作为左侧和右侧空格和输出也应包含带有and的左侧和右侧空格

Input :

s = 'n && && && && && &&n'

My code :

m=re.sub(r'\s[&&]\s', ' and ',s)
print(m)

My output :

n && && && && && &&n

Expected output :

n and and and and and &&n

推荐答案

我认为您需要空格的后视和前视表达式,这样匹配就不会重叠,因为re.sub()将"返回通过用替换repl替换string中最左侧的非重叠出现的pattern而获得的字符串".

有关这些表达式的解释,请参见here.


>>> import re
>>> s = 'n && && && && && &&n'
>>> m = re.sub(r'(?<=\s)&&(?=\s)', 'and', s)
>>> print(m)
n and and and and and &&n

如果你想在字符串的末尾或开头捕获&&,那么按照附近@tim biegeleisen的建议使用\S.

Python-3.x相关问答推荐

确定字符串的长度并提取前15或14个字符

如何从拼图分区数据集中读取数据到Polar

如何定义既允许固定单词又允许模式的pydanti.BaseModel?

PythonPandas 创建一个列并添加到DataFrame

将列表项的极列水平分解为新列

如何计算累积几何平均数?

查找值始终为零的行 pandas

ValueError at /register/ 视图authenticate.views.register_user 未返回HttpResponse 对象.它返回 None 相反

selenium 无法执行网站上最简单的功能

Python webdrivermanager 和 Chrome 115.0 的 URL https://chromedriver.storage.googleapis.com/LATEST_RELEASE_115.0.5790 错误没有此类驱动程序

如何将多输入数据加载器传递给单输入模型

如何将 WebDriver 传输到导入的测试?

裁剪复数以解决 exp 中的溢出错误

使用 RANSAC 在激光雷达点云中查找电力线

找到操作系统的图片文件夹的 CLI

在 sklearn.decomposition.PCA 中,为什么 components_ 是负数?

为什么 Django South 1.0 使用 iteritems()?

sys.stdin.readline() 读取时没有提示,返回 'nothing in between'

在 WSL (Ubuntu) 中为 python3 安装 venv

python中的绝对导入是什么?