user3342411
user3342411

Reputation: 1

Python self value is not properly coming in member function?

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..

Upvotes: 0

Views: 77

Answers (2)

unutbu
unutbu

Reputation: 880587

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']

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124170

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

Upvotes: 2

Related Questions