1

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?

0

4 Answers 4

3

Why not:

import re

text = 'hello world'
res = re.sub('([aeiou])', r'\1f\1', text)
# hefellofo woforld
Sign up to request clarification or add additional context in comments.

1 Comment

This is a better approach than mine, +1
1
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!

Comments

1

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'))

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.