开发者

Replace dictionary values

Hey all, I'm trying to work on a simple script that takes a string and replaces each letter in the string. What I've tried doing is creating a dictionary for each values such as


mydict = {"a":"1", "b":"2"}
And I've tried some for loops but so far no luck. The idea I have in my head is for each value in the string, replace that val开发者_StackOverflow中文版ue with what I have in the dictionary. But so far no luck.


If all you are doing is replacing one letter with another, simply use string.maketrans and string.translate.

Here's a pretty simple example of how to use them


Sounds like you are trying to do something like this?

base = "foobar"
new = ''
replacements = {
    'o': 1,
    'b': 'x'
}

for c in base:
    new += str(replacements.get(c, c))

print new

>>> f11xar

reversed:

target = "foobar"
replacements = {
    'o': '1',
    'b': 'x'
}

for k,v in replacements.iteritems():
    target = target.replace(k, v)

print target
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜