0
class XXFile:

    def __init__( self, FileName ):
        self.File = FileName

    def Process ( self ):
        for self.Line in  open ( self.File ):
          self.SetFlds()

    def SetFlds ( self ):
        Write2Log ( "Inside the SetFlds()->Line::[" + self.Line + "]"  )
        Write2Log ( "Test->Line22,34::[" + self.Line [ 22 : 34 ].strip() + "]" )

MyFile = XXFile( "a.txt" )
MyFile.Process()

OUTPUT

2014-02-26T20:41:47| Inside the SetFlds()->Line::[XXXX           9999999                       XXXXXXXXXXXXXXXXXXXXXXX   ABCDE]
2014-02-26T20:41:47| Test->Line22,34::[]

Why am I not getting characters from 22 of length 34? I am getting full all characters in self.Lin in setflds() and but slicing of self.Line is not working..

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    It's working fine, except the slice contains only spaces and `strip()` removes all of them. Also, *please* don't use capitals in variable and method names, in Python you only use them for names of classes. – RemcoGerlich Feb 26 '14 at 13:39

2 Answers2

2

Your line has got whitespace on it; characters 22 through to 34 are either spaces or tabs, and the .strip() call removes these characters, leaving you with an empty string:

>>> line = 'XXXX           9999999                       XXXXXXXXXXXXXXXXXXXXXXX   ABCDE'
>>> line[22:34]
'            '
>>> len(line[22:34])
12
>>> line[22:34].strip()
''
>>> len(line[22:34].strip())
0
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

Why am I not getting characters from 22 of length 34?

self.Line[22:34] gets (at most) 34-22 = 12 characters starting at index location 22. To get 34 characters, use

self.Line[22:56]

In [18]: line = 'XXXX           9999999                       XXXXXXXXXXXXXXXXXXXXXXX   ABCDE'

In [20]: line[22:56].strip()
Out[20]: 'XXXXXXXXXXX'

See here for an explanation of Python slicing.


Also, you might be better off using str.split:

In [21]: line.split()
Out[21]: ['XXXX', '9999999', 'XXXXXXXXXXXXXXXXXXXXXXX', 'ABCDE']
Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677