简体   繁体   中英

Replace “&&” with “and” using re.sub in python.

I have a string containing && .
I want to replace all && which have SPACE on both right and left side.

Sample String :

x&& &&&  && && x 

Desired Output :

x&& &&&  and and x


My Code :

import re
print re.sub(r'\B&&\B','and','x&& &&&  && && x')

My Output

x&& and&  and and x

Please suggest me, how can I prevent &&& from getting replaced with and& .

You can search using this lookaround regex:

(?<= )&&(?= )

and replace by and

Code:

p = re.compile(ur'(?<= )&&(?= )', re.IGNORECASE)
test_str = u"x&& &&& && && x"

result = re.sub(p, "and", test_str)

RegEx Demo

You don't need a regex for this, just split will do this. ie, split your input string according to the spaces then iterate over each item in the list then make it to return and only if the item is equal to && else return than particular item. Finally join the returned list with spaces.

>>> s = 'x&& &&&  && && x'
>>> l = []
>>> for i in s.split():
    if i == '&&':
        l.append('and')
    else:
        l.append(i)


>>> ' '.join(l)
'x&& &&& and and x'

OR

>>> ' '.join(['and' if i == '&&' else i for i in s.split()])
'x&& &&& and and x'

sample input

s = "x&& &&&  && && x"

you can use the lookbehind and lookhead assertion of regex

>>> print( re.sub(r"(?<=\s)&&(?=\s)", 'and',s))
x&& &&&   and   and  x

Here regular expression (?<=\\s)&&(?=\\s) means, && will be preceded and followed by space(\\s).

(?<=...)

this is a positive lookbehind assertion which makes sure the matched string is preceded by ...

For Example : (?<=x)abc will find a match in xabc

(?=...)

this is a lookahead assertion which make sure that matched string is followed by ...

For example: abc (?=xyz) will match 'abc ' only if it's followed by 'xyz'.

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