Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #101097 > unrolled thread

Re: Newbie: Check first two non-whitespace characters

Started byCameron Simpson <cs@zip.com.au>
First post2016-01-01 17:30 +1100
Last post2016-01-01 17:30 +1100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Newbie: Check first two non-whitespace characters Cameron Simpson <cs@zip.com.au> - 2016-01-01 17:30 +1100

#101097 — Re: Newbie: Check first two non-whitespace characters

FromCameron Simpson <cs@zip.com.au>
Date2016-01-01 17:30 +1100
SubjectRe: Newbie: Check first two non-whitespace characters
Message-ID<mailman.134.1451629854.11925.python-list@python.org>
On 31Dec2015 18:38, MRAB <python@mrabarnett.plus.com> wrote:
>On 2015-12-31 18:18, otaksoftspamtrap@gmail.com wrote:
>>I need to check a string over which I have no control for the first 2 non-white space characters (which should be '[{').
>>
>>The string would ideally be: '[{...' but could also be something like
>>'  [  {  ....'.
>>
>>Best to use re and how? Something else?
>>
>I would use .split and then ''.join:
>
>>>> ''.join(' [ { ....'.split())
>'[{....'

This presumes it is ok to drop/mangle/lose the whitespace elsewhere in the 
string. If it contains quoted text I'd expect that to be very bad.

>It might be faster if you provide a maximum for the number of splits:
>>>> ''.join(' [ { ....'.split(None, 1))
>'[{ ....'

Not to mention safer.

I would use lstrip and startswith:

  s = lstrip(s)
  if s.startswith('['):
    s = s[1:].lstrip()
    if s.startswith('{'):
      ... deal with s[1:] here ...

It is wordier, but far more basic and direct.

Cheers,
Cameron Simpson <cs@zip.com.au>

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web