Reputation: 2611
I'm pretty sure that my question is very straightforward but I cannot find the answer to it. Let's say we have an input string like:
input = "This is an example"
Now, I want to simply replace every word --generally speaking, every substring using a regular expression, "word" here is just an example-- in the input with another string which includes the original string too. For instance, I want to add an @
to the left and right of every word in input. And, the output would be:
output = "@This@ @is@ @an@ @example@"
What is the solution? I know how to use re.sub
or replace
, but I do not know how I can use them in a way that I can update the original matched strings and not completely replace them with something else.
Upvotes: 0
Views: 860
Reputation: 16583
You can match only word boundaries with \b
:
import re
input = "This is an example"
output = re.sub(r'\b', '@', input)
print(output)
@This@ @is@ @an@ @example@
Upvotes: 0
Reputation: 3219
You can use capture groups for that.
import re
input = "This is an example"
output = re.sub("(\w+)", "@\\1@", input)
A capture group is something that you can later reference, for example in the substitution string. In this case, I'm matching a word, putting it into a capture group and then replacing it with the same word, but with @
added as a prefix and a suffix.
You can read about regexps in python more in the docs.
Upvotes: 1
Reputation: 520978
Here is an option using re.sub
with lookarounds:
input = "This is an example"
output = re.sub(r'(?<!\w)(?=\w)|(?<=\w)(?!\w)', '@', input)
print(output)
@This@ @is@ @an@ @example@
Upvotes: 1
Reputation: 1383
This is without re library
a = "This is an example"
l=[]
for i in a.split(" "):
l.append('@'+i+'@')
print(" ".join(l))
Upvotes: 0