[Tutor] Fw: list.replace -- string.swap
alan.gauld at btinternet.com
Thu Mar 19 00:52:30 CET 2009
It wasn't my question :-)
Forwarding to list...
Author of the Learn To Program website
----- Original Message ----
> From: Ricardo Aráoz <ricaraoz at gmail.com>
> Subject: Re: [Tutor] Fw: list.replace -- string.swap
> >>>> Also: How would perform string.swap(s1, s2) in the following cases:
> >> Here I mean exchanging s1 and s2 occurrences all along a string. As an
> >> in a text containing numerous formatted numbers, switch from english to
> >> format:
> >> 1,234,567.89
> >> 1.234.567,89
> >> meaning exchange '.' and ','.
> >>>> * There is no secure 'temp' char, meaning that
> >>>> s.replace(s1,temp).replace(s2,s1).replace(temp,s2)
> >>>> will fail because any char can be part of s.
> >> The use of a temp char for marking places of one the chars to be swapped is a
> >> common trick. But if the text can contain any char (even chr(0)), then there
> >> char you can safely use as temp.
> >> The only workaround I know is to pass through lists. Then swap on the list,
> >> using eg None as temp item, and glue back the result to a string. But you
> >> them a replace method on lists, hence my previous question ;-)
> >>>> * Either s1 or s2 can be more than a single char.
> >> More difficult, cause you cannot simple list() the string. It must split on
> >> and s2, but keeping the delimiters! There is no option afaik for that in
> >> string.split -- too bad! So that you must split it manually at start and end
> >> each instance of s1 and s2. Or there are other algorithms I cannot figure
> >> What I was asking for.
> So NOW I get your question!!!
> It's easy :
> >>> import string
> >>> mystr = '1,234,567.89'
> >>> mystr.translate(string.maketrans('.,', ',.'))
> Any length of string to be translated, any length of translation tables
> (not only two values, any amount of them).
More information about the Tutor