You are not logged in.
Pages: 1
Hi, to the python gurus...
in tcl you can do:
string map {aa 2a bb 2b a A b B} aaabbb => 2aA2bB
i.e. replace multiple sbstrings in a string in one command. How can it be done in python?
10x!
Offline
i know python but i dont know tcl so i couldn't understand your code, could you please explain that code
In a world without walls,who need windows?
Offline
I don't of anything like that in python but there are dictionaries:
>>> dict = {'aa':'2a', 'bb':'2b', 'a':'A', 'b':'B'}
>>> dict['aa']
'2a'
or map using a dictionary:
>>> def foo(x):
... dict = {'aa':'2a', 'bb':'2b', 'a':'A', 'b':'B'}
... return dict[x]
...
>>> map(foo, ['aa', 'a', 'bb', 'b'])
['2a', 'A', '2b', 'B']
Offline
Here's explanation:
"string map" allows to perform multiple replace of substringS at once. In the code:
string map {aa 2a bb 2b a A b B} aaabbb
"aa" is replaced with "2a", "bb" with "2b", "a" with "A" and "b" with "B". Given string "aaabbb" the result will be "2aA2bB"
Hope it's clear now
Offline
In the string module it is a method, translate, maybe that is what you are looking for?
Offline
No, translate is not good enough. It can only replace 1 char by other char, "string map" can do it with substrings
Shortest code i can think of is:
s = 'aaabbb'
for f,t in (('aa',2A'), ('bb',2B'), ('a','A'), ('b','B')): s = s.replace(f, t)
Offline
Pages: 1