Strange behaviour with a for loop.

Cameron Simpson cs at zip.com.au
Sat Jan 4 02:52:54 EST 2014


On 04Jan2014 16:54, Sean Murphy <mhysnm1964 at gmail.com> wrote:
> Thanks everyone.
> 
> Mark thanks for the correction on the ':'. Since I didn't cut and copy, rather typed it out. Errors crept in. :-)
> 
> another question in relation to slicing strings. If you want to get a single character, just using the index position will get it. If I use the following, shouldn't it also work? when I use Python 3.3, it didn't provide anything.
> 
> a = "test.txt"
> print a[3]
> result is:
> 
> 't

As expected, yes?

> print a[3:1]
> Nothing is printed. 
> 
> print a[3:2]
> Nothing is printed.

These are not requests for 1 and 2 character strings. They are
requests for the character in the span from, respectively, 3 to 1
and from 3 to 2. Important: counting FORWARDS. So: zero length
strings.

> print a[3:-1]
> t.tx is printed.
> 
> Why doesn't the positive number of characters to be splice return anything while the negative value does?

-1 is shorthand for len(a)-1
It is often convenient to refer to a position from the end of the
array instead of the start.

So this means: [3:7], so positions 3,4,5,6.

> sorry about these basic questions. I do like the splice feature within Python. Also what is the best method of testing for a blank string?

Well, and empty string: a == '' or len(a) == 0.
And, because an "if" tests the nonzeroness of a single argument and
an empty string has length zero, you can also go:

  if a:
    print "long string", a
  else:
    print "empty string"

OTOH, if you mean a "blank string" to mean "containing only
whitespace", you can use the string method "isspace", which tests
that all characters are whitespace and that the string is not empty.
The doco for isspace() actually says:

  Return true if there are only whitespace characters in the string
  and there is at least one character, false otherwise.

So you might write:

  if not a or a.isspace():
    print "blank string:", repr(a)

Really you'd want to put that it a (trivial) function:

  def isblank(s):
    ''' Test that the string `s` is entirely blank.
    '''
    return not s or s.isspace()

That way you can write isblank() all through your program and control the
precise meaning by modifying the function.

Cheers,
-- 

The perl5 internals are a complete mess. It's like Jenga - to get the perl5
tower taller and do something new you select a block somewhere in the middle,
with trepidation pull it out slowly, and then carefully balance it somewhere
new, hoping the whole edifice won't collapse as a result.
- Nicholas Clark, restating an insight of Simon Cozens



More information about the Python-list mailing list