[Tutor] Final review

meenu ravi meenuravi89 at gmail.com
Tue May 6 07:13:26 CEST 2014


Hi Scott,

The variable greeting is of type "string".

>>> greeting = "Hello world"

>>> type(greeting)

<type 'str'>


The len(string) will count each character in the value of variable
"greeting" starting from '1'.

H - 1

e - 2

l - 3

l - 4

0 - 5

space - 6(Space and special characters are also counted)

w - 7

o - 8

r - 9

l - 10

d - 11



So the len(greeting) returns 11.

>>> len(greeting)

11

But while accessing with the index, indexing starts with '0'. Like,

>>> greeting.index('H')

0

>>> greeting.index('e')

1

>>> greeting.index('l')

2


Likewise, the index of d, which is the last word in the word "Hello world"
is 10.

So, the maximum index you can access in the word "Hello world" is 10. But
when you try to give the command,

>>> greeting [len(greeting)]

It is trying to access the character at the position "11", where the string
"Hello world" doesn't contain any value in the index "11" and the maximum
index is 10. So it throws the following error.

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

IndexError: string index out of range

So always the maximum index will be length - 1. So if you want to access
the last character of the string "Hello world", give the command:

>>> greeting[len(greeting)-1]

'd'

Hope this helps

Thanks
On 6 May 2014 09:35, "Scott W Dunning" <scott.w.d at cox.net> wrote:

>
> On May 1, 2014, at 5:30 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>
> Awesome, thanks everyone!  I understand lists a lot better now.
>
> I have another question.  I don’t understand why below would give an error?
>
> >>>  greeting = 'Hello World’
> >>>  greeting [len(greeting)]
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140506/54a9bc4e/attachment.html>


More information about the Tutor mailing list