1

I have a question, if I have

h = "hello world"
print (h.count(''))

That prints 12.

But if i do

print (h[11]) 

I get an IndexError: string index out of range

I don't understand the reason.

What does the count function count when passing an empty string?

Isra
  • 182
  • 2
  • 14
  • 2
    Empty strings exist at both ends of your string, and between each pair of characters within it: so the result is the string length plus one. – jasonharper Aug 10 '20 at 21:31

2 Answers2

0

The String Hello World Can only be indexed up to 10. Remember that indexes start at zero

H the first character is 0 and d at the end is 10

when you do count(''), it includes a blank space after and before the String, so it adds two extra increments.

So you can do len(h)-1 or (h.count('')-2) to show the last element of the strings index.

Note len() shows how many elements are in a list not the index of the last one. The last element of a string or list is len()-1

Alexander
  • 1,051
  • 1
  • 8
  • 21
0

The reason it prints 12 is that there are empty strings in between every letter, and at both sides. Here is a diagram:

  All empty strings!
^h^e^l^l^o^ ^w^o^r^l^d^

it looks weird, but every ^ is an empty sn empty string, and if you count them, there are 12.

The reason you are getting the error is that a string is just an array of characters, so it is zero-indexed, meaning that the first element is index 0, the second at index 1, and so on. Here is a diagram:

-------------------------------------
a | b | c | d | e | f | g | h | i | j
-------------------------------------
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
-------------------------------------

As you can see, the tenth element (j), is at index 9, so trying to get index 10 would result in an error.

cs1349459
  • 911
  • 9
  • 27