[英]How can I replace two different sub strings in a string by using re.sub() in python?
這里的任務是替換'&&','||' 分別用“和”,“或”。 我一次只能更改一個邏輯運算符。 我嘗試應用re.sub()方法一段時間,結果是只包含“或”的輸出。
輸入樣例:
11
a = 1;
b = input();
if a + b > 0 && a - b < 0:
start()
elif a*b > 10 || a/b < 1:
stop()
print set(list(a)) | set(list(b))
樣本輸出:
a = 1;
b = input();
if a + b > 0 and a - b < 0: # '&&' changed to ' and '
start()
elif a*b > 10 or a/b < 1: # '||' changed to ' or '
stop()
print set(list(a)) | set(list(b))
我的代碼:
import re
N = int(raw_input())
print N
lines = ""
for i in range(0,N):
lines+=raw_input()+"\n"
lines = re.sub(r"\s&&\s", ' and ' , lines, flags=re.IGNORECASE)
print lines
我的輸出:
11 #Actually this should be eliminated
a = 1;
b = input();
if a + b > 0 and a - b < 0: # '&&' changed to ' and '
start()
elif a*b > 10 || a/b < 1:
stop()
print set(list(a)) | set(list(b))
在re.sub
使用lambda函數
>>> import re
>>> s = 'foo && bar || buzz'
>>> re.sub(r'\s(&&|\|\|)\s', lambda m: ' and ' if m.group(1) == '&&' else ' or ', s)
'foo and bar or buzz'
>>>
正則表達式=> \\s(&&|\\|\\|)\\s
\\s
匹配空格字符 (&&|\\|\\|)
匹配並捕獲&&
或||
字符。 函數=> lambda m: ' and ' if m.group(1) == '&&' else ' or '
所有匹配的字符都作為m
匹配對象傳遞給匿名函數。 我們可以通過在match對象上調用group(index)
來獲取所有匹配的字符。 即, m.group()
或m.group(0)
將顯示所有字符,而m.group(1)
將顯示第一個捕獲組捕獲的字符。
現在,它檢查所拍攝的字符等於&&
,如果是的話那么它會替換特定的字符and
否則它會返回or
因而被替換。
雖然可以使用正則表達式,但實際上非常簡單的列表理解加上' '.join()
也可以工作:
>>> string = 'foo && bar || buzz'
>>> ' '.join(['and' if w == '&&' else 'or' if w == '||' else w for w in string.split()])
'foo and bar or buzz'
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.