Tab expansion problem or ..?

Peter Otten __peter__ at web.de
Fri Feb 27 16:41:50 EST 2004


Tony C wrote:

> I've written a program which reads a text file in , and writes it out
> to a new filename.
> 
> When the program encounters a line which contains a specific text
> label-, I read in the hex number adjacent to the label, convert the
> number to decimal, then write the line of text to the output file.
> 
> Essentially, the output file is mostly identical to the input file,
> with the exception of the hex numbers being converted to decimal.
> 
> The problem I'm having is getting the exact location of the hex
> numbers.
> 
> fhIn = open("input.txt")
> 
> for line in fhIn:
>   if 'HEXNUM' in line:
>     Hexloc = line.find('HEXNUM')
>     print"\n%s" % line[:Hexloc]
> 
> The index returned by find() does not seem to be accurate.
> 
> When I display the line using the offset (Hexloc), the text displayed
> is many characters away from the text label 'HEXNUM'.
> 
> 
> So I then tried
>  
> fhIn = open("input.txt")
> 
> for line in fhIn:
>   if 'HEXNUM' in line.expandtabs():
>     Hexloc = line.find('HEXNUM')
>     print"\n%s" % line[:Hexloc]
> 

You are throwing away the result of line.expandtabs() in the above code.
Therefore the expansion effects neither the printed line nor the Hexloc
index. It should rather be (untested)

for line in fhIn:
    if "HEXNUM" in line:
        line = line.expandtabs()
        Hexloc = line.find("HEXNUM")
        print "\n%s" % line[:Hexloc]

> and I've tried passing numbers from 1-4 to expantabs, all with
> different results.
> 
> I've verified that there are tab characters in the input file, by
> using an editor which can display the "whitespace characters" as
> visible symbols.
> 
> 
> Am I overlooking something painfully obvious here ?
> 
> 
> thanks in advance




More information about the Python-list mailing list