简体   繁体   中英

How can I replace two different sub strings in a string by using re.sub() in python?

Here task is to replace '&&', '||' with ' and ', ' or ' respectively. I am able to change only one logical operator at once. And I tried applying re.sub() method for times and it resulted a output of containing only 'or'.

Sample Input:

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)) 

Sample Output:

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))

My Code:

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

My output:

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))

Use lambda function in re.sub

>>> 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'
>>> 

Regex => \\s(&&|\\|\\|)\\s

  • \\s matches space character
  • (&&|\\|\\|) matches and captures either && or || characters.

Function => lambda m: ' and ' if m.group(1) == '&&' else ' or '

  • All the matched characters are passed to the anonymous function as m match object. We can get all the matched chars by calling group(index) on match object. ie, m.group() or m.group(0) will display all the characters and m.group(1) would display the chars which are captured by the first capturing group.

  • Now it checks for the captured chars is equal to && , if so then it would replace that particular chars with and else it would return or and thus gets replaced.

While you can use regular expression, a realitivly simple list comprehension plus ' '.join() would also work:

>>> string = 'foo && bar || buzz'
>>> ' '.join(['and' if w == '&&' else 'or' if w == '||' else w for w in string.split()])
'foo and bar or buzz'
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM