Regular expression, "except end of string", question.

Peter Hansen peter at engcorp.com
Thu Jun 17 01:58:46 CEST 2004


Derek Basch wrote:

> I have a string like:
> 
> string = "WHITE/CLARET/PINK/XL"
> 
> which I need to alter to this format:
> 
> string = "WHITE-CLARET-PINK/XL"
> 
> I developed the below functions to do so. However, something is wrong 
> with my regular expression. 

As they say, if you have a problem and think a regular expression
is the best way to solve it, you might now have two problems...

Do you always want to exclude the last "/" ?  How about this
instead:

s = 'white/claret/pink/xl'

s2 = s.split('/')  # temporary list

# join all but last with hyphens, add last after slash
s = '-'.join(s2[:-1]) + '/' + s2[-1]

# s is now 'white-claret-pink/xl'

Depending on what the format really is (e.g. is the /XL
actually optional?) it might be simpler or harder than
this.

An re can be made to work too, probably, but perhaps it
won't be very clear.

-Peter



More information about the Python-list mailing list