1

i just started python after php and javascript but i am confused in this easy concept....i already search a lot about this on tutorialpoints or w3school but i find nothing

here is the example code

var1 = 'Hello-World!'
print("var1[:6]: ", var1[:6])

This code will print the output as Hello- but here where is the W word because a string always start from 0 value so w will also be printed .....

anyways now i decided to print every word seperately

print("var1[0]: ", var1[0])
print("var1[1]: ", var1[1])
print("var1[2]: ", var1[2])
print("var1[3]: ", var1[3])
print("var1[4]: ", var1[4])
print("var1[5]: ", var1[5])
print("var1[6]: ", var1[6])

and the output is

var1[0]:  H
var1[0]:  e
var1[0]:  l
var1[0]:  l
var1[0]:  o
var1[0]:  -
var1[0]:  W

now i am really confused that why W is not printed in my first example code ?

glibdud
  • 7,550
  • 4
  • 27
  • 37
Nalin Nishant
  • 716
  • 1
  • 5
  • 20

1 Answers1

1

List slicing goes from the first index until the last index. In other words, the slice

var1[0:6]  # same as var1[:6]

covers the indices 0 through 5, but not 6.

The reason W is not printed is because W is index 6. If you want to include W, then you need to do var1[0:7].

This is intuitive, because if you do, say, var1[m:n], then you get a substring of exactly m - n length. Similarly, if I say I want var1[:6], I'm saying I want the first 6 characters of var1. Not the seventh character, which would have index 6.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53