Sorry if this has been asked before, I looked and couldn't find it.
I've been asked to make a algorithm that changes a character on a string. Here is an example:
abc
def
I want to chance every 'a' to 'd', every 'd' to 'a', every 'b' to 'e', every 'e' to 'b' and so on. So if my input is "abc def", my output is "def abc".
I tried:
def change(string, dic):
for i, c in dic.iteritems():
string = string.replace(i, c)
return string
dic = {'a':'d','b':'e','c':'f',
'd':'a','e':'b','f':'c'}
string = 'abc def'
print change(string,dic) #returns abc abc
I didn't think python would check twice each character on the string (if this is what happened).
everything I tried didn't work, can you guys give me some advice?
Thanks.
There is str.translate
method for this exact job:
>>> import string
>>> t = string.maketrans("abcdef", "defabc")
>>> "abc def".translate(t)
'def abc'
string.maketrans(from, to) Return a translation table suitable for passing to translate(), that will map each character in from into the character at the same position in to; from and to must have the same length.
string.translate(s, table[, deletechars]) Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. If table is None, then only the character deletion step is performed.
You can use the get
method from your dictionary. The first parameter is the key to check for, the second is the value to use if the key is not found. So if the key is found, the corresponding dictionary value is swapped in, otherwise the original character is left. So iterating through all of the letters in this manner, you can join
the result and that's your answer.
def change(string, dic):
return ''.join(dic.get(i,i) for i in string)
>>> string = 'abc def'
>>> d = {'a':'d', 'b':'e', 'c':'f', 'd':'a', 'e':'b', 'f':'c'}
>>> change(string, d)
'def abc'
This works on Python 3, not sure if "character in dic" has to be changed for Python 2.
def change(string, dic):
string_new = ""
for character in string:
if character in dic:
string_new = string_new + dic[character]
else:
string_new = string_new + character
return string_new
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.