简体   繁体   中英

Multiple string replacements in Python

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?

Why not:

import re

text = 'hello world'
res = re.sub('([aeiou])', r'\1f\1', text)
# hefellofo woforld
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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM