Extract the middle N chars of a string
Random832
random832 at fastmail.com
Wed May 18 17:28:43 EDT 2016
On Wed, May 18, 2016, at 11:47, Steven D'Aprano wrote:
> So after spending a ridiculous amount of time on what seemed like it
> ought
> to be a trivial function, and an embarrassingly large number of
> off-by-one
> and off-by-I-don't-even errors, I eventually came up with this:
>
> def mid(string, n):
> """Return middle n chars of string."""
> L = len(string)
> if n <= 0:
> return ''
> elif n < L:
> Lr = L % 2
> a, ar = divmod(L-n, 2)
> b, br = divmod(L+n, 2)
> a += Lr*ar
> b += Lr*br
> string = string[a:b]
> return string
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 funneling the special cases through the slice statement at the end
rather than simply returning string and '' because it's conceptually
nicer and because it could be used for other purposes than slicing
strings.
More information about the Python-list
mailing list