-1
s = 'your'
print(s.count(''))

I expected the output to be 4, but it gave me an output 5. What's the logic behind it?

Ocaso Protal
  • 19,362
  • 8
  • 76
  • 83
Arhten
  • 1
  • 1
  • 1
    What are you trying to count? – B Remmelzwaal Mar 08 '23 at 15:07
  • If you wanted to know how long the string is then *len(s)*. If you wanted to know how many spaces are in the string then *s.count(' ')* (note the space between the two single-quotes). The former would reveal 4 and the latter zero – DarkKnight Mar 08 '23 at 15:12

1 Answers1

2

I'm not sure why you expect 4. There are 5 empty strings "in" s, with (conventionally) one in each of the following positions:

  1. Before y
  2. Between y and o
  3. Between o and u
  4. Between u and r
  5. After r

If you were only expecting empty strings in the interior, you should have expected 3, ignoring both the first and last occurrences.

(I say "conventionally", because really, you could claim there are infinite empty strings in any of the 5 positions, since x + "" == "" + x == x. But since assuming one empty string per slot is sufficient to let all our nice laws about string concatenation hold, we make the simplest assumption.)

chepner
  • 497,756
  • 71
  • 530
  • 681
  • I got it! I, initially, left out the empty string after before y. Your answer helped me. Thank you! – Arhten Mar 08 '23 at 15:13