Extract the middle N chars of a string

Steven D'Aprano steve at pearwood.info
Wed May 18 21:03:27 EDT 2016


On Thu, 19 May 2016 07:28 am, Random832 wrote:

> My take:
> 
> def mid(string, n):
>     if n > len(string): n = len(string)
>     if n <= 0: n = 0
>     offset = int(len(string)/2+n/2)
>     return string[offset:offset+n]
> 
> It doesn't get the same result as yours when the length is odd and N is
> even, but the problem is ambiguous there and I feel like my algorithm is
> more clear.

I'm not sure that "the algorithm is more clear" is the right way to judge
this. Especially when your function doesn't even come *close* to meeting
the requirements. It doesn't even return substrings of the right length!

py> for i in range(8):
...     print mid('abcdefg', i)
...
<BLANKLINE>
e
ef
fg
fg
g
g
<BLANKLINE>
py> for i in range(7):
...     print mid('abcdef', i)
...
<BLANKLINE>
d
ef
ef
f
f
<BLANKLINE>


I sympathise, I really do, because as my first post says, this really does
seem like it ought to be a no-brainer trivial exercise in slicing. Instead,
it is remarkably subtle and tricky to get right.




-- 
Steven




More information about the Python-list mailing list