user3857330
user3857330

Reputation: 3

Replacing strings in its entirity

I want to replace words if it matches with a string entirely in Python.

Suppose,

 st = 'Length Le'.

I want to replace all words 'le' with <=

Result has to be

'Length <='

I tried this with replace() and re.sub() but it gives me

'<=ngth <='

Is there any inbuilt function for this operation?

Upvotes: 0

Views: 49

Answers (4)

0xhughes
0xhughes

Reputation: 2753

Slice it!

st = 'Length Le'
if st.endswith(' Le'):
    st = st[0:len(st)-3] + " <="
print st
Length <=

Takes the variable st, checks to see if it ends with " Le", if true, using string slicing the ending " Le" is removed and the " <=" is then added. This is considering your input for var st will always be static in form and adhere to a certain format.

Upvotes: 0

Basic
Basic

Reputation: 26766

Try something like this...

import re
s = "Length Le"
re.sub(r'\bLe\b', '<=', s)

It will match the regular expression \bLe\b and replace all matches with <=. The expression means "Le" where it's not surrounded by alphanumeric characters. In effect, where Le is surrounded by whitespace or punctuation.

The Python documentation on Regex is worth a read, specifically look at \b which matches a word boundary.

Upvotes: 1

Use the regular expression \b to match a word boundary - such a zero-width string that on one side has non-word character, and on the other side has a word-character.

Optionally also use re.I for ignore case, and re.U for Unicode string match if you have non-Ascii words, and you are using Python 2...

Thus we get a regex \ble\b which stands for a word boundary, followed by l, e, and a word boundary. With re.I the case is ignored so l will also match L and e will also match E.

Example:

>>> import re
>>> string = "Length Le le ale"
>>> re.sub(r'\ble\b', '<=', string, flags=re.I|re.U)
'Length <= <= ale'

Upvotes: 0

Blair
Blair

Reputation: 6693

If you always know that le will be a word of its own, you can replace it when it has spaces before and after. The caveat is you will have to change your string from 'Length le' to 'Length le '.

>>> s1 = 'Length le '
>>> s2 = 'length le '
>>> s3 = ' le length'
>>> s1.replace(' le ', '<= ')
'Length <='
>>> s2.replace(' le ', '<= ')
'length <='
>>> s3.replace(' le ', '<= ')
'<= length'

Upvotes: 0

Related Questions