You are not logged in.

#1 2006-07-21 15:26:09

drakosha
Member
Registered: 2006-01-03
Posts: 253
Website

python question

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

#2 2006-07-21 20:03:16

Titus
Member
From: Izmir
Registered: 2006-05-11
Posts: 120
Website

Re: python question

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

#3 2006-07-21 22:32:30

T-Dawg
Forum Fellow
From: Charlotte, NC
Registered: 2005-01-29
Posts: 2,736

Re: python question

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

#4 2006-07-23 11:59:06

drakosha
Member
Registered: 2006-01-03
Posts: 253
Website

Re: python question

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 smile

Offline

#5 2006-07-23 12:54:34

lessthanjake
Member
From: Norway
Registered: 2005-11-09
Posts: 319
Website

Re: python question

In the string module it is a method, translate, maybe that is what you are looking for?

Offline

#6 2006-07-23 13:57:36

drakosha
Member
Registered: 2006-01-03
Posts: 253
Website

Re: python question

No, translate is not good enough. It can only replace 1 char by other char, "string map" can do it with substrings sad
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

Board footer

Powered by FluxBB