Reputation: 3187
This is my code:
line = input('Line: ')
if 'a' in line:
print(line.replace('a', 'afa'))
elif 'e' in line:
print(line.replace('e', 'efe'))
It's obviously not finished, but I was wondering, let's say there was an 'a' and an 'e', how would I replace both of them in the same statement?
Upvotes: 1
Views: 118
Reputation: 23480
my_string = 'abcdefghij'
replace_objects = {'a' : 'b', 'c' : 'd'}
for key in replace_objects:
mystring = mystring.replace(key, replace_objects[key])
If you've got a load of replacements to do and you want to populate the replacement list after a while it's quite easy with a dictionary. Altho regexp or re
is prefered.
Upvotes: 0
Reputation: 142106
Why not:
import re
text = 'hello world'
res = re.sub('([aeiou])', r'\1f\1', text)
# hefellofo woforld
Upvotes: 3
Reputation: 129487
let's say there was an 'a' and an 'e', how would I replace both of them in the same statement?
You can chain the replace()
calls:
print(line.replace('a', 'afa').replace('e', 'efe'))
Upvotes: 1
Reputation: 3187
line = input('Line: ')
line = line.replace('a', 'afa')
line = line.replace('e', 'efe')
line = line.replace('i', 'ifi')
line = line.replace('o', 'ofo')
line = line.replace('u', 'ufu')
print(line)
Got it!
Upvotes: 1