[英]How to replace numbers with a string that are surrounded by double quotes in python?
[英]Python regex replace space from string if surrounded by numbers, but not letters
我的输入变量为字符串:
'12345 67890'
'abc 123'
'123 abc'
'abc def'
我的目的是如果两侧的字符都是数字而不是字母,则删除字符之间的空格。 我正在考虑使用re模块,也许是re.sub()函数或类似的东西。
所需的输出:
'1234567890'
'abc 123'
'123 abc'
'abc def'
谢谢
regex
和后向使用regex
:
>>> import re
>>> re.sub(r'(?<=\d)\s(?=\d)', '', '12345 67890')
'1234567890'
>>> re.sub(r'(?<=\d)\s(?=\d)', '', 'abc 123')
'abc 123'
>>> re.sub(r'(?<=\d)\s(?=\d)', '', '123 abc')
'123 abc'
>>> re.sub(r'(?<=\d)\s(?=\d)', '', 'abc def')
'abc def'
>>> re.sub(r'(?<=\d)\s(?=\d)', '', '123 abc 1234 456')
'123 abc 1234456'
您不需要正则表达式
if all(part.isdigit() for part in data.split()):
data = data.replace(" ", "")
您可以使用以下正则表达式:
re.sub('^(\d+) (\d+)$', r'\1\2', s)
这是一个正则表达式,可以执行您想要的操作:
re.sub(r"(?P<digit_before>\d)\s(?P<digit_after>\d)",r"\g<digit_before>\g<digit_after>",s)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.