Lin Ma
Lin Ma

Reputation: 10139

string replace in Python 2.7

Using Python 2.7 and working on below string replace problem, wondering if any better ideas in terms of algorithm space complexity and algorithm time complexity?

I create an additional list to represent result since string Python 2.7 is immutable and I also created an additional dictionary to speed-up look-up for character replacement table.

In the example, From: "lod" and To: "xpf" means when met with l, replace to x ; and when met with o, replace to p; and when met with d, replace to f.

'''
Given "data", "from", and "to" fields, replaces all occurrences of the characters in the "from" field in the "data" field, with their counterparts in the "to" field.
Example:
Input:
Data: "Hello World"
From: "lod"
To: "xpf"
Output:
"Hexxp Wprxf"
'''

from collections import defaultdict
def map_strings(from_field, to_field, data):
    char_map = defaultdict(str)
    result = []
    for i,v in enumerate(from_field):
        char_map[v]=to_field[i]
    for v in data:
        if v not in char_map:
            result.append(v)
        else:
            result.append(char_map[v])

    return ''.join(result)

if __name__ == "__main__":
    print map_strings('lod', 'xpf', 'Hexxp Wprxf')

Upvotes: 1

Views: 2894

Answers (2)

ebeneditos
ebeneditos

Reputation: 2612

You can also use replace:

def map_strings(from_field, to_field, data):
    for f, t in zip(from_field, to_field):
        data = data.replace(f, t)
    return data

Upvotes: 2

PM 2Ring
PM 2Ring

Reputation: 55469

There's efficient machinery in the standard modules for this. You first build a translation table using string.maketrans, then call the str.translate method:

import string

trans = string.maketrans('lod', 'xpf')
print "Hello World".translate(trans)

output

Hexxp Wprxf

But if you want to do it manually, here's a way that's a little more efficient than your current code:

def map_strings(from_field, to_field, data):
    char_map = dict(zip(from_field, to_field))
    return ''.join([char_map.get(c, c) for c in data])

s = map_strings('lod', 'xpf', 'Hello World')
print s    

Note that in Python 3 the string.maketrans function no longer exists. There's now a str.maketrans method, with slightly different behaviour.

Upvotes: 4

Related Questions