Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #108773
| Path | csiph.com!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail |
|---|---|
| From | Ian Kelly <ian.g.kelly@gmail.com> |
| Newsgroups | comp.lang.python |
| Subject | Re: Extract the middle N chars of a string |
| Date | Wed, 18 May 2016 10:34:12 -0600 |
| Lines | 84 |
| Message-ID | <mailman.10.1463589299.27390.python-list@python.org> (permalink) |
| References | <573c8e97$0$1596$c3e8da3$5496439d@news.astraweb.com> <CALwzidnPrBmp1_qgy7uARYAd2pYn9UR545+9tP4kfrNYnYVYkQ@mail.gmail.com> |
| Mime-Version | 1.0 |
| Content-Type | text/plain; charset=UTF-8 |
| X-Trace | news.uni-berlin.de sO/dP7D4vchReMt9tJibvwO0UVqO+HofbEmDAtnTQrGg== |
| Return-Path | <ian.g.kelly@gmail.com> |
| X-Original-To | python-list@python.org |
| Delivered-To | python-list@mail.python.org |
| X-Spam-Status | OK 0.001 |
| X-Spam-Evidence | '*H*': 1.00; '*S*': 0.00; 'elif': 0.04; 'seemed': 0.07; 'cc:addr:python-list': 0.09; '"""return': 0.09; 'ambiguity': 0.09; 'subject:string': 0.09; 'received:209.85.218': 0.10; 'def': 0.13; 'wed,': 0.15; '2016': 0.16; 'cc:name:python': 0.16; 'received:io': 0.16; 'received:psf.io': 0.16; 'slicing:': 0.16; 'wrote:': 0.16; 'string': 0.17; 'odd': 0.18; 'cc:2**0': 0.20; 'cc:addr:python.org': 0.20; 'function,': 0.22; 'am,': 0.23; 'seems': 0.23; 'this:': 0.23; 'header:In-Reply-To:1': 0.24; 'message-id:@mail.gmail.com': 0.27; 'print': 0.30; 'getting': 0.33; 'problem': 0.33; "d'aprano": 0.33; 'errors,': 0.33; 'steven': 0.33; 'received:google.com': 0.35; 'but': 0.36; 'received:209.85': 0.36; 'subject:: ': 0.37; 'received:209': 0.38; 'skip:p 20': 0.38; 'subject:the': 0.39; 'easy': 0.60; 'different': 0.63; 'to:none': 0.91 |
| DKIM-Signature | v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20120113; h=mime-version:in-reply-to:references:from:date:message-id:subject:cc; bh=QrXLNZnWkwNkqVxlIHBYKHijZONcrrkfLfPlEHfHzrE=; b=bMm0G2XOFCLLzU7xH4FE+U2obFD4Hvr3Ti/5vK9jXsVsRLAQ9gPsM2PZMxU70pmuUq HFvwcodA3FtaIdA6UZxqXnd3yNiDJChDLZiylGed2HvLTxUmU6GoGk2al2DIoRjOEMZH 7UGV+A9kSkrehQ4C2dJdsigmQZvJYiVDt2cks2cOUsueT8o9sjgzajfwlugrQnkbf4cr kvHZzcwtGs4eKJKY0C0kEl87N1Hoqvc5BwtDQ3XQbuD1C8REL7BA/RweTzLNLH0u6fAa QgiUrKHx2i1JOdZ5+S9Srhy8xYHv0MGBdE0Eb/q17OEGlPa6/rv5/SNIBwifSBHS4whe kuUg== |
| X-Google-DKIM-Signature | v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20130820; h=x-gm-message-state:mime-version:in-reply-to:references:from:date :message-id:subject:cc; bh=QrXLNZnWkwNkqVxlIHBYKHijZONcrrkfLfPlEHfHzrE=; b=IW4YaLfwIUu1BKIUbLpN/RdLd2lrHaQJrNYqAHYOSdy7abU47xIow5djcHaW+f8zbI FUw7O3ZM3rjfsABWpaGnAKs1et+nBzIwkb2yhA8FUtpzat1NtF97wwZoU8VjSsN0zvBp Mh8kYRMrnnocbATcBPJj5Pk8io4lPkXd0WibfSwu4ZzBAWGtLPd6Go50hDBZsDX/D3d2 c8Ixavlk07+QEK3QOZmfZ9YSXt805M6ctUdZFGmtbf18lYhdAJCGITV/v4C4Tvqfzk2e OW6ZShXVmIfb2CWYPUIVCkYJiM17QtBSnybF1GzyTFoFYl5IW048wo0jnRYpjIhkDewN 322A== |
| X-Gm-Message-State | AOPr4FVOP6TbpUpAm93NU7n6p+J7j5j9WS90e0o0KvTSI/Dgn1bt3IojIhoWUIs1okCPX9D/LsZScV23+U5JNg== |
| X-Received | by 10.202.87.12 with SMTP id l12mr1674935oib.54.1463589292257; Wed, 18 May 2016 09:34:52 -0700 (PDT) |
| In-Reply-To | <573c8e97$0$1596$c3e8da3$5496439d@news.astraweb.com> |
| X-BeenThere | python-list@python.org |
| X-Mailman-Version | 2.1.22 |
| Precedence | list |
| List-Id | General discussion list for the Python programming language <python-list.python.org> |
| List-Unsubscribe | <https://mail.python.org/mailman/options/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe> |
| List-Archive | <http://mail.python.org/pipermail/python-list/> |
| List-Post | <mailto:python-list@python.org> |
| List-Help | <mailto:python-list-request@python.org?subject=help> |
| List-Subscribe | <https://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=subscribe> |
| X-Mailman-Original-Message-ID | <CALwzidnPrBmp1_qgy7uARYAd2pYn9UR545+9tP4kfrNYnYVYkQ@mail.gmail.com> |
| X-Mailman-Original-References | <573c8e97$0$1596$c3e8da3$5496439d@news.astraweb.com> |
| Xref | csiph.com comp.lang.python:108773 |
Show key headers only | View raw
On Wed, May 18, 2016 at 9:47 AM, Steven D'Aprano <steve@pearwood.info> wrote:
> Extracting the first N or last N characters of a string is easy with
> slicing:
>
> s[:N] # first N
> s[-N:] # last N
>
> Getting the middle N seems like it ought to be easy:
>
> s[N//2:-N//2]
>
> but that is wrong. It's not even the right length!
>
> py> s = 'aardvark'
> py> s[5//2:-5//2]
> 'rdv'
>
>
> 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
>
>
> which works for me:
>
>
> # string with odd number of characters
> py> for i in range(1, 8):
> ... print mid('abcdefg', i)
> ...
> d
> de
> cde
> cdef
> bcdef
> bcdefg
> abcdefg
> # string with even number of characters
> py> for i in range(1, 7):
> ... print mid('abcdef', i)
> ...
> c
> cd
> bcd
> bcde
> abcde
> abcdef
>
>
>
> Is this the simplest way to get the middle N characters?
There's an ambiguity in the problem description when N and the length
of the string have different parity, but how about:
def mid(string, n):
L = len(string)
a = (L - n) // 2
return string[a:a+n]
py> for i in range(1, 8):
... print(mid('abcdefg', i))
...
d
cd
cde
bcde
bcdef
abcdef
abcdefg
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Extract the middle N chars of a string Steven D'Aprano <steve@pearwood.info> - 2016-05-19 01:47 +1000
Re: Extract the middle N chars of a string Ian Kelly <ian.g.kelly@gmail.com> - 2016-05-18 10:34 -0600
Re: Extract the middle N chars of a string Peter Otten <__peter__@web.de> - 2016-05-18 18:41 +0200
Re: Extract the middle N chars of a string Peter Otten <__peter__@web.de> - 2016-05-18 18:54 +0200
Re: Extract the middle N chars of a string Steven D'Aprano <steve@pearwood.info> - 2016-05-19 11:37 +1000
Re: Extract the middle N chars of a string MRAB <python@mrabarnett.plus.com> - 2016-05-18 18:00 +0100
Re: Extract the middle N chars of a string Steven D'Aprano <steve@pearwood.info> - 2016-05-19 11:34 +1000
Re: Extract the middle N chars of a string Random832 <random832@fastmail.com> - 2016-05-18 17:28 -0400
Re: Extract the middle N chars of a string Steven D'Aprano <steve@pearwood.info> - 2016-05-19 11:03 +1000
Re: Extract the middle N chars of a string Grant Edwards <grant.b.edwards@gmail.com> - 2016-05-18 21:35 +0000
Re: Extract the middle N chars of a string Steven D'Aprano <steve@pearwood.info> - 2016-05-19 10:48 +1000
Re: Extract the middle N chars of a string Wildman <best_lay@yahoo.com> - 2016-05-18 23:17 -0500
Re: Extract the middle N chars of a string boB Stepp <robertvstepp@gmail.com> - 2016-05-20 23:00 -0500
csiph-web