简体   繁体   中英

Slice two ranges from one line in text file

I'm trying to extract two ranges per line of an opened text file in python 3 by looping through.

The application has a Entry widget and the value is stored in self.search . I then loop through a text file which contains the values I want, and write out the results to self.searchresults and then display in a Textbox.

I've tried variations of the third line below but am not getting anywhere.

I want to write out characters in each line from 3:24 and 81:83 ...

for line in self.searchfile:
    if self.search in line:
        line = line[3:24]+[81:83]
        self.searchresults.write(line+"\n")

Here's an abridged version of the text file I'm working with (original here ):

! Author: Greg Thompson  NCAR/RAP
!         please mail corrections to gthompsn (at) ucar (dot) edu
! Date: 24 Feb 2015
! This file is continuously maintained at:
! http://www.rap.ucar.edu/weather/surface/stations.txt
!
! [... more comments ...]

ALASKA             19-SEP-14                                                  
CD  STATION         ICAO  IATA  SYNOP   LAT     LONG   ELEV   M  N  V  U  A  C
AK ADAK NAS         PADK  ADK   70454  51 53N  176 39W    4   X     T          7 US
AK AKHIOK           PAKH  AKK          56 56N  154 11W   14   X                8 US
AK AKUTAN           PAUT               54 09N  165 36W   25   X                7 US
AK AMBLER           PAFM  AFM          67 06N  157 51W   88   X                7 US
AK ANAKTUVUK PASS   PAKP  AKP          68 08N  151 44W  642   X                7 US
AK ANCHORAGE INTL   PANC  ANC   70273  61 10N  150 01W   38   X     T  X  A    5 US

You're not far off - your problem is that you need to specify what you're slicing each time you slice it:

for line in self.searchfile:
    if self.search in line:
        line = line[3:24] + line[81:83]
        self.searchresults.write(line+"\n")

... but you'll probably want to separate the two fields with a space:

        line = line[3:24] + " " + line[81:83]

However, if you find yourself using + more than once to construct a string, you should think about using Python's built-in string-formatting abilities instead (and while you're at it, you can add that newline in the same operation):

for line in self.searchfile:
    if self.search in line:
        formatted = "%s %s\n" % (line[3:24], line[81:83])
        self.searchresults.write(formatted)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM