Home > Back-end >  Can we replace 'e' with 'o' and 'o' with 'e' in "Hello
Can we replace 'e' with 'o' and 'o' with 'e' in "Hello

Time:06-08

I tried this with replace function but of no use.

s = "Hello World"
s = s.replace("e","o").replace("o","e")
print(s)
#output= Helle Werld

Then I tried this with translate function

s = "hello world"
dictionary = {'e':'o', 'o': 'e'}
transTable = s.maketrans(dictionary) 
s = s.translate(transTable)
print(s)
#output= Holle Werld

Can we simplify this?

CodePudding user response:

s = "hello world"
t = s.maketrans("eo", "oe") 
print(s.translate(t))

output = holle werld

CodePudding user response:

This is the simplest Translate method till now.(Thanks @hiro-protagonist)

s = "hello world"
print(s.translate(s.maketrans("eo", "oe")))

Or you can also try this instead using Replace method

s = "hello world"
s=s.replace("e","\e").replace("o","\o").replace("\e","o").replace("\o","e")
print(s)
  • Related