-2

So im not an python developer but was reading a source code of a python console app which i would like to write it in c# and experiment with it. But i couldn't understand this expression:

result = content[:4] + sig + content[19:]

Can someone explain me what is [:4] and [19:].

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
AquaDev
  • 62
  • 7

1 Answers1

0

They are list slices:

content[:4]

I'm assuming you're familiar with the concept of lists(/arrays). This syntax is a list slice, in this case the it returns elements 1-4 of the list. In fact, it gives indexes 0-3. Python counts from 0, and the 4 in the slice is non-inclusive. The slice is equivalent to [0:4] -> items at indexes 0-4, non inclusive so as I said that means indexes 0-3

The same goes for:

content[19:]

This means it'll return every element from index 19 (20th item) to the end of the list. The starting value is inclusive so it is actually index 19, not 20

List slices return a list too.

List indexing, if you're interested is similar but uses just 1 number to get the index instead of that colon : notation:

content[3]

Would give the 4th item (index 3) of the list, assuming it exists.

N Chauhan
  • 3,407
  • 2
  • 7
  • 21
  • Yes im familiar with arrays as im a c# developer and thanks for explaining. Marked as right answer. Edit: will mark in 5 min – AquaDev Sep 03 '18 at 19:03
  • Thanks, see here for extra info: https://stackoverflow.com/a/509295/9917694 – N Chauhan Sep 03 '18 at 19:04