1

I am currently studying Python at school. I don't understand what the book is trying to explain and my instructor isn't very helpful. The book gives the following example:

usr_text = input('Enter a string: ')
print()

first_half = usr_text[:len(usr_text)//2]
last_half = usr_text[len(usr_text)//2:]

print('The first half of the string is "{}"'.format(first_half))
print('The second half of the string is "{}"'.format(last_half))

I don't understand what

[:len(usr_text)//2]

&

[len(usr_text)//2:]

does. Would anyone mind explaining what's happening there and why it's used? Thank you!

frankie
  • 21
  • 4
  • 5
    Does this answer your question? [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) – Countour-Integral Jan 19 '21 at 19:52
  • `//` is an integer division (as opposed to floating-point `/`), so you are slicing to half of the string by measuring its length and dividing that by 2 – ti7 Jan 19 '21 at 19:53
  • `foo[:x]` is equivalent to `foo[0:x]` which means "the elements from `0` up to but not including `x`". Similarly `foo[x:]` means "the elements from `x` to the end of the sequence" – Cory Kramer Jan 19 '21 at 19:54
  • Thank you all! The link to the similar question helped a lot. – frankie Jan 19 '21 at 20:02

0 Answers0