[Baypiggies] string question
Tim Hatch
tim at timhatch.com
Wed Apr 6 00:54:21 CEST 2011
On 4/5/11 1:39 PM, Simeon Franklin wrote:
> On Tue, Apr 5, 2011 at 1:25 PM, Vikram K <kpguy1975 at gmail.com
> <mailto:kpguy1975 at gmail.com>> wrote:
>
> Given a string and some indices, how do i change upper characters
> corresponding to some position(s) in the string to lower characters?
> I tried and failed.
Your way is reasonable. Depending on how sparse your modifications are,
you could also build up the string another way using slicing -- the core
of my suggestion is
>>> x = 'EPSPVRYDNLSR'
>>> x[:5]+x[5:7].lower()+x[7:]
'EPSPVryDNLSR'
But you'd want to build it up in a list or use cStringIO, like
>>> buf = []
>>> buf.append(x[:5])
>>> buf.append(x[5:7].lower())
>>> buf.append(x[7:])
>>> ''.join(buf)
'EPSPVryDNLSR'
And adapting for your method of indexing might be interesting. If you
have start-stop positions that are non-overlapping and half-open, this
could be as easy as (completely untested):
prev_end = 0
end = len(x)
for start, end in index_pairs:
if prev_end != start:
buf.append(x[prev_end:start])
buf.append(x[start:end].lower())
prev_end = end
buf.append(x[end:])
Tim
More information about the Baypiggies
mailing list