Reputation: 23
I need to write a program that replaces characters in a string, I need to do it without using replace(). This is not a problem as translate() works just fine. However, I need to replace multiple characters and right now, I can only replace one at a time, as in only one of the 'if' statements runs. It looks somewhat like this:
#constants
X = 'xex'
Z = 'zaz'
#then the user provides a string using input()
def newest_string():
for i in string:
if i == 'x':
new_word = word.translate({ord(i): X for i in 'x'})
continue
elif i == 'z':
new_word = word.translate({ord(i): Z for i in 'z'})
continue
#then there are many more similar statements using translate() because
there are many characters that need to be changed
else:
continue
return string
Note that str.translate
converts all occurrences of the specified characters, so the for
loop is just a waste of efficiency.
Also, {ord(i): X for i in 'x'}
and {ord(i): Z for i in 'z'}
are the exact equivalent of {ord('x'): X}
and {ord('z'): X}
, as there is only one character both 'x'
and 'z'
.
Upvotes: 0
Views: 66
Reputation: 27547
Here is how you can use a dict()
with more than one conversion:
#constants
X = 'xex'
Z = 'zaz'
#then the user provides a string using input()
def newest_string(word):
new_word = word.translate({ord('x'): X, ord('z'): Z})
return new_word
print(newest_string('I am at the zoo. So exciting!'))
Output:
I am at the zazoo. So exexciting!
Upvotes: 2