簡體   English   中英

如何在python中使用re.sub()替換字符串中的兩個不同子字符串?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM