Frage

I am new in python and doing some testing I found this.

>item="testing315testing08634567890"
>item.index("086")
17
>item[17:10]
''
>item[17:]
'08634567890'

I don't understand why is not working, while with other strings it works. Note that if I do this...

> item[4:10]
'ing315'

Are the numbers in the middle causing troubles? Is this a bug?. Did I missing something? I am using Python 3.3

War es hilfreich?

Lösung

The end index of a list slice is a position greater than the start index, is not the size of the slice! so you want something like this:

item[17:len(item)]

Notice that this is exactly equivalent to the previous snippet:

item[17:]

The start and end indexes of a slice such as alist[a:b] should be interpreted like this: the slice starts at the item in the a position in alist and ends one element before the b position in alist. Both a and b are indexes in alist.

Andere Tipps

When you index a string with a range like that, you have to place the lower bound first and the higher bound second, like so:

item[10:17]

Think of it as saying "I want this string from a to b (where b is excluded)" as in:

some_string[a:b]

If you want the string to the end (or from the beginning) you can simply omit the bound.

Here's an example:

my_string = "test"
my_string[:2]       ==> "te"
my_string[2:]       ==> "st"
my_string[:]        ==> "test"
my_string[1]        ==> "e"
my_string[1:3]      ==> "es"

The second number in your index must be larger than the first number. For example:

item[17:17]
item[17:10]
item[17:17-1]

will all return,

''

If you want to get the 10 characters after the matched index you could do something like this:

>item="testing315testing08634567890"
>item[item.index("086") : item.index("086")+10]
'0863456789'

As others have stated, the second argument is an ending index. but a nice hack works too:

list[x:x+len]

so if you want 10 chars, starting at 17 like in the example:

item[17:17+10] will give you the desired result.

note: this will not cause any index errors but if the string is shorter than the end index (17+10 == 27) it will yield the same result as item[17:]. the accepted answer solves the proposed question, but if you wanted 10 from the middle:

item="testing315testing08634567890some_other_stuff_here"

item[17:] == "08634567890some_other_stuff_here"
item[17:17+10] == "08634567890"

the 17+10 notation is kept because it clearly shows the intention and allows for easy substitution of variables which might not be known until runtime.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top