473,887 Members | 2,319 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

String negative indices?

I'm just starting out on Python, and am stumped by what appears an oddity in the way negative indices are handled.

For example, to get the last character in a string, I can enter "x[-1]". To get the 2nd and 3rd to last, I can enter x[-3:-1] etc. This is fine.

Logically, I should be able to enter x[-2:-0] to get the last and next to last characters. However, since Python doesn't distinguish between positive and negative zero, this doesn't work. Instead, I have to enter x[-2:].

With simple constants, this is ok, but it's a little more annoying when the start and end of the range are in variables somewhere. The only way I can find of making this work without lots of special-case "if" logic is to translate negative subscripts to positive, which kinda defeats the purpose of the negative subscripts anyway.

Is there some magic I'm missing here? Wouldn't it actually be better for Python to treat 0 as a special case here, so that x[-2:0] and x[-2:] generated the same result?

--Tim
Jun 23 '06 #1
11 3745
dr*******@comca st.net wrote:
Is there some magic I'm missing here? Wouldn't it actually be better for Python to treat 0 as a
special case here, so that x[-2:0] and x[-2:] generated the same result?


No, since x[-2:0:-1] already has meaning and it isn't what you want.
--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
The mind is not a vessel to be filled but a fire to be kindled.
-- Plutarch
Jun 23 '06 #2
drtimh...@comca st.net wrote:
I'm just starting out on Python, and am stumped by what appears an oddity in the way negative indices are handled.

For example, to get the last character in a string, I can enter "x[-1]". To get the 2nd and 3rd to last, I can enter x[-3:-1] etc. This is fine.

Logically, I should be able to enter x[-2:-0] to get the last and next to last characters. However, since Python doesn't distinguish between positive and negative zero, this doesn't work. Instead, I have to enter x[-2:].

With simple constants, this is ok, but it's a little more annoying when the start and end of the range are in variables somewhere. The only way I can find of making this work without lots of special-case "if" logic is to translate negative subscripts to positive, which kinda defeats the purpose of the negative subscripts anyway.

Is there some magic I'm missing here? Wouldn't it actually be better for Python to treat 0 as a special case here, so that x[-2:0] and x[-2:] generated the same result?

--Tim


x[-2:None]

I'm not sure if it qualifies as "magic" but you're right, it's not more
obvious than 0 would be.

George

Jun 23 '06 #3
dr*******@comca st.net wrote:
Logically, I should be able to enter x[-2:-0] to get the last and next to last characters. However, since Python doesn't distinguish between positive and negative zero, this doesn't work. Instead, I have to enter x[-2:].


Hooray! Logically there is no such thing as positive or negative zero,
or did I miss something in the primary?

PS. x[len(x)-2 : len(x)-0]

cheers,
fw

Jun 23 '06 #4
On Fri, 23 Jun 2006 02:17:39 -0700, Filip Wasilewski wrote:
dr*******@comca st.net wrote:
Logically, I should be able to enter x[-2:-0] to get the last and next to last characters. However, since Python doesn't distinguish between positive and negative zero, this doesn't work. Instead, I have to enter x[-2:].


Hooray! Logically there is no such thing as positive or negative zero,
or did I miss something in the primary?


No, not in the primary, or even in the secondary, but possibly in the
tertiary.

For many purposes, it doesn't make sense to distinguish +0 from -0. But
for other purposes, it does.

For instance, in floating point maths, it may be useful for negative
numbers that underflow to be distinguished from positive numbers that
underflow. See, for example,
http://www.savrola.com/resources/negative_zero.html

In statistical mechanics, some systems can have negative absolute
temperatures, including negative zero. Counter-intuitively, negative
absolute temperatures aren't colder than absolute zero, but hotter than
any positive temperature. So, strangely enough, a temperature of -0K is
hotter than a infinitely hot temperature!

(Those wacky physicists and their mathematics...)

See http://en.wikipedia.org/wiki/Negativ...te_temperature for a
description. And in case you think this is just a modern version of angels
dancing on the head of a pin, negative absolute temperatures are essential
for lasers.

In pure mathematics, zero is usually considered unsigned. However, in
"non-standard analysis" using so-called "hyperreal" or "surreal" numbers,
mathematicians use infinitesimals which are [sloppy hand-waving] like
signed zeroes. To put it another way, only slightly less sloppy,
infinitesimals are zero, but not all the same zero.

When doing calculus with complex numbers, it is very important to
distinguish which direction you are taking your limits in, and so
lim z -> 0+0i is not necessarily the same as lim z -> 0-0i.
--
Steven

Jun 23 '06 #5
Steven D'Aprano wrote:
On Fri, 23 Jun 2006 02:17:39 -0700, Filip Wasilewski wrote:
dr*******@comca st.net wrote:
Logically, I should be able to enter x[-2:-0] to get the last and next to last characters. However, since Python doesn't distinguish between positive and negative zero, this doesn't work. Instead, I have to enter x[-2:].
Hooray! Logically there is no such thing as positive or negative zero,
or did I miss something in the primary?


No, not in the primary, or even in the secondary, but possibly in the
tertiary.

For many purposes, it doesn't make sense to distinguish +0 from -0. But
for other purposes, it does.


I believe you will agree that this is mostly a matter of notation of
some fact rather than really trying to sign zero.
For example I use to denote numbers that approach zero from "the right
side" by x -> [0 uppercase +], which is definitely harder to type and
display in poor man's text editor than x -> +0.
Otherwise I should also rethink the meaning of positive (>0) and
negative (<0) numbers (at least where such relations are defined).

[...]
In statistical mechanics, some systems can have negative absolute
temperatures, including negative zero. Counter-intuitively, negative
absolute temperatures aren't colder than absolute zero, but hotter than
any positive temperature. So, strangely enough, a temperature of -0K is
hotter than a infinitely hot temperature!


Yeah, this is really cool ;-)

--
Filip

"During board meeting: We have great news. Our earnings reached highest
value ever - a positive 0."

Jun 24 '06 #6
On Sat, 24 Jun 2006 05:36:17 -0700, Filip Wasilewski wrote:
Steven D'Aprano wrote:
On Fri, 23 Jun 2006 02:17:39 -0700, Filip Wasilewski wrote:
> dr*******@comca st.net wrote:
>
>> Logically, I should be able to enter x[-2:-0] to get the last and next to last characters. However, since Python doesn't distinguish between positive and negative zero, this doesn't work. Instead, I have to enter x[-2:].
>
> Hooray! Logically there is no such thing as positive or negative zero,
> or did I miss something in the primary?


No, not in the primary, or even in the secondary, but possibly in the
tertiary.

For many purposes, it doesn't make sense to distinguish +0 from -0. But
for other purposes, it does.


I believe you will agree that this is mostly a matter of notation of
some fact rather than really trying to sign zero.


No.

In floating point, +0 *really is* different from -0 -- the two floats
have different bit patterns. Floating point libraries must be specifically
programmed to ignore that difference, making zero treated differently than
other floats. That's -- usually -- a good thing.

In mathematics, well, maybe... certainly in the Real number system, there
is no difference, and +0 and -0 are just two ways of writing the same
thing. In the hyperreals, +0 and -0 are the same, but there are
infinitesimals which are different, and signed. I don't know enough about
the surreals to comment. In matrix maths, there are an infinite number of
different matrices where all the elements are zero -- they are all
distinct, different, zeroes.

And in "the real world", all numbers are an abstraction anyway, so I'm
not too worried about correspondence to reality. If mathematicians find a
use for distinguishing +0 from -0 (as the statistical physicists have
done) they will treat them as "really" different. If they don't, they
won't.
--
Steven.

Jun 25 '06 #7
Steven D'Aprano wrote:
In mathematics, well, maybe... certainly in the Real number system, there
is no difference, and +0 and -0 are just two ways of writing the same
thing. In the hyperreals, +0 and -0 are the same, but there are
infinitesimals which are different, and signed. I don't know enough about
the surreals to comment. In matrix maths, there are an infinite number of
different matrices where all the elements are zero -- they are all
distinct, different, zeroes.


What do you even mean by that? By "matrix maths," do you just mean
matrices whose elements are reals, or something else?

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
My heart is pure as the driven slush.
-- Tallulah Bankhead
Jun 25 '06 #8
On Sat, 24 Jun 2006 21:15:17 -0700, Erik Max Francis wrote:
Steven D'Aprano wrote:
In mathematics, well, maybe... certainly in the Real number system, there
is no difference, and +0 and -0 are just two ways of writing the same
thing. In the hyperreals, +0 and -0 are the same, but there are
infinitesimals which are different, and signed. I don't know enough about
the surreals to comment. In matrix maths, there are an infinite number of
different matrices where all the elements are zero -- they are all
distinct, different, zeroes.


What do you even mean by that? By "matrix maths," do you just mean
matrices whose elements are reals, or something else?


Given any matrix M, there is a matrix Z such that M+Z = M. That matrix Z
is equivalent to zero in the reals, where x+0 = x.

In the reals, there is only one "zero", 0.

In matrices, there are an infinite number of "zeroes":

1x1 matrix: [0]
1x2 matrix: [0 0]
1x3 matrix: [0 0 0]
2x2 matrix:
[0 0]
[0 0]

etc. It is true that none of these are exactly equivalent to +0 and -0,
but my point was that there can be more than one distinct zero in pure
mathematics, and there is nothing wrong with the concept of a system with
more than one distinct zero.
--
Steven

Jun 25 '06 #9
Steven D'Aprano wrote:
Steven D'Aprano wrote:
In matrix maths, there are an infinite number of
different matrices where all the elements are zero -- they are all
distinct, different, zeroes.

What do you even mean by that? By "matrix maths," do you just mean
matrices whose elements are reals, or something else?


Given any matrix M, there is a matrix Z such that M+Z = M. That matrix Z
is equivalent to zero in the reals, where x+0 = x.


Ah, of course. I knew this, I just misinterpreted your "distinct,
different, zeroes" as referring to the elements but not the matrices.
Just a misunderstandin g.

Every zero matrix is an additive identity, and there are an infinite
number of them. That's certainly true.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
There's a reason why we / Keep chasing morning
-- Sandra St. Victor
Jun 25 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
2158
by: dan | last post by:
I was recently surprised, and quite shocked in fact, to find that Python treats negative indices into sequence types as if they were mod(length-of-sequence), at least up to -len(seq). This fact is *deeply* buried in the docs, and is not at all intuitive. One of the big advantages of a high-level language such as Python is the ability to provide run-time bounds checking on array-type constructs. To achieve this I will now have to...
19
2616
by: David Abrahams | last post by:
Can anyone explain the logic behind the behavior of list slicing with negative strides? For example: >>> print range(10) I found this result very surprising, and would just like to see the rules written down somewhere. Thanks,
9
3446
by: Randell D. | last post by:
Folks, I can program fairly comfortably in PHP and can, for the most part using these skills and others that I've picked up over the years manage to read/understand most code in Javascript... so I'm just asking for a few pointers (or the full solution if you have the time) for what I want to do. Basically, I want to write a javascript wherby I only need to pass it the names of form fields - then my javascript will check each form field...
108
6505
by: Bryan Olson | last post by:
The Python slice type has one method 'indices', and reportedly: This method takes a single integer argument /length/ and computes information about the extended slice that the slice object would describe if applied to a sequence of length items. It returns a tuple of three integers; respectively these are the /start/ and /stop/ indices and the /step/ or stride length of the slice. Missing or out-of-bounds indices are handled in a manner...
19
78866
by: Paul | last post by:
hi, there, for example, char *mystr="##this is##a examp#le"; I want to replace all the "##" in mystr with "****". How can I do this? I checked all the string functions in C, but did not find one.
29
4340
by: zoro | last post by:
Hi, I am new to C#, coming from Delphi. In Delphi, I am using a 3rd party string handling library that includes some very useful string functions, in particular I'm interested in BEFORE (return substring before a pattern), AFTER (return substring after a pattern), and BETWEEN (return substring between 2 patterns). My questions are: 1. Can any tell me how I can implement such functionality in C#? 2. Is it possible to add/include function...
8
5174
by: Joakim Hove | last post by:
Hello, I have the following code: #define N 99 double *ptr; double *storage; int index; storage = calloc(N , sizeof(double));
1
4837
by: illegal.prime | last post by:
So I see from the documentation here: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemCollectionsArrayListClassBinarySearchTopic.asp That the code uses the less than operator: int myIndex=myList.BinarySearch( myObject ); if ( myIndex < 0 ) when using the BinarySearch method and in my own experience I see that sometimes it returns other negative values (other than -1).
2
7261
by: smichr | last post by:
It seems to me that the indices() method for slices is could be improved. Right now it gives back concrete indices for a range of length n. That is, it does not return any None values. Using an example from clpy about this the indices for a 'None, None, -2' slice for a range of length 10 are given as '9, -1, -2'. The problem is that these concrete values cannot be fed back into a slice so that a slice will extract the same elements that...
0
9957
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
10877
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10434
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9593
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7988
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7143
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5810
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6011
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3245
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.