0

I'd like to know how the following string processing works for the text file given below. It tries to get what follows in lines starting with "name:..."

The part of the 4th line

line[len('name:'):]

does not seem very intuitive in helping me understand how it works.It seems like its getting the length of 'name:'. Also what is the extra : following ) for ?

for line in lines:
    line=line.rstrip('\n')    # assuming it came from a file, remove newline
    if line.startswith('name:'):
        print('The name is '+line[len('name:'):])
    else:
        print('The content is '+line)

It parses a text file with the following content

name:english
1001Nights 
A Night at the Call Center
Grammar
name:science
Engineering
Biology
Physics
name:maths
Algebra
Geometry

Thanks in Advance for all your help

Dhiwakar Ravikumar
  • 1,983
  • 2
  • 21
  • 36
  • Rather than give a constant number to slice with, the code uses `len('name:')` to count the number of characters to remove from the start of the line. `len('name:')` is 5, since there are 5 characters so it removes the first 5 characters from the line by slicing with `line[5:]`. See the linked post for details on how the slice notation works. – Martijn Pieters Mar 08 '15 at 18:35

1 Answers1

0

It is getting the length of 'name:'. You could replace len('name:') with the literal number 5 and the code would work the same.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384