I wonder what is the corresponding code for the following code in python. I want to check the charactares backword in a string. An exampel if I have a str="anything" and i want to add a '2' if the character is vowel and if the prefix is vowel and suffix is vowel so I want to add '2ä before and after the charctar so the result will be str="a0n0y0th0i0ng". I hope that I could clarify it as much as possible. In c++ we can write str.back(), is there anything like this in python?
Asked
Active
Viewed 212 times
-2
-
I mean add a '0' not '2' sorry for this. – Mohammad eyad harfoush Dec 12 '20 at 23:21
1 Answers
0
You can use regex replacement.
import re
my_str = 'anything'
output = re.sub(r'([aeiouy])', r'0\g<1>0, my_str)
# '0a0n0y0th0i0ng'
You could follow that up with, say, output.strip('0')
to get rid of the character at the front if you really don't want it there.
re.sub()
takes a regex as its first argument (we submit a capture group for a single letter, which can be any vowel), and the replacement as the second argument. The replacement in this case, r'0\g<1>0
, literally means to insert 0
, then the captured group 1 (which is the vowel), then another 0
(see this answer for more details).

Green Cloak Guy
- 23,793
- 4
- 33
- 53