![](/img/trans.png)
[英]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.