[Tutor] Fw: list.replace -- string.swap

Ricardo Aráoz ricaraoz at gmail.com
Thu Mar 19 02:46:27 CET 2009


ALAN GAULD wrote:
> It wasn't my question :-)
>
> Forwarding to list...
>
>  
> Alan Gauld
> Author of the Learn To Program website
> http://www.alan-g.me.uk/
>
>
>
>
> ----- 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 
>>>>         
>> example, 
>>     
>>>> in a text containing numerous formatted numbers, switch from english to 
>>>>         
>> european 
>>     
>>>> 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 
>>>>         
>> no 
>>     
>>>> 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 
>>>>         
>> need 
>>     
>>>> 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 
>>>>         
>> s1 
>>     
>>>> 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 
>>>>         
>> of 
>>     
>>>> each instance of s1 and s2. Or there are other algorithms I cannot figure 
>>>>         
>> out. 
>>     
>>>> 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('.,', ',.'))
>>>>>           
>> '1.234.567,89'
>>
>> Any length of string to be translated, any length of translation tables
>> (not only two values, any amount of them).
>>
>> HTH
>>
>> Ricardo.
>>     
Sorry Alan, was meant to the list. Just pressed reply and  forgot here
it does not go to the list.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090318/d57f6690/attachment.htm>


More information about the Tutor mailing list