may be a bug in string.rstrip

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Nov 23 12:06:11 EST 2007


Scott SA a écrit :
> On 11/23/07, kyo guan (kyoguan at gmail.com) wrote:
> 
>>   Please look at this code:   
>>
>>>>> 'exe.torrent'.rstrip('.torrent')
>> 'ex'           <-----  it should be 'exe', why?
>>
>> but this is a right answer:
>>
>>>>> '120.exe'.rstrip('.exe')        
>> '120'          <------ this is a right value.
>>
>>   there is a bug in the rstrip, lstrip there isn't this problem.
> 
> Since your error has been addressed, I'd like to offer a point not expressed by others (that I've seen yet).
> 
> To perform this task, there are a couple of options i.e. string.replace:
> 
>     >>> string.replace('120.exe','.exe','')
>     '120'
> 
> ... but it has a side-effect of mid-string replacements:
> 
>     >>> string.replace('123.exe.more','.exe','')
>     '123.more'
> 
> or maybe:
>     
>     >>> if x[-4:] == '.exe': 
>     ...     x[:-4]
>     '123'
> 
> ... is functional, but not elegant i.e. quick 'n dirty esp. as one line.
> 
> The better option, IMO, is probably to use regex. 

You forgot at least the simplest solution:

import os.path
os.path.splitext('132.ext')[0]

HTH



More information about the Python-list mailing list