简体   繁体   中英

Python - Replacing characters in a list

I'm working on a Python script which opens a DBF file, and then from that creates a text output of the contents (either .txt or .csv).

I've now managed to get it writing the output file, but I need to replace the space character in one of the database fields (It's a UK Car registration number, eg I need "AB09 CDE" to output as "AB09CDE") but I've been unable to work out how to do this as it seems to be nested lists. The field is rec[7] in the code below.

if __name__ == '__main__':
 import sys, csv
 from cStringIO import StringIO
 from operator import itemgetter

 # Read a database
 filename = 'DATABASE.DBF'
 if len(sys.argv) == 2:
     filename = sys.argv[1]
 f = open(filename, 'rb')
 db = list(dbfreader(f))
 f.close()
 fieldnames, fieldspecs, records = db[0], db[1], db[2:]

 # Remove some fields that we don't want to use...
 del fieldnames[0:]
 del fieldspecs[0:]
 #Put the relevant data into the temporary table
 records = [rec[7:8] + rec[9:12] + rec[3:4] for rec in records]


 # Create outputfile
 output_file = 'OUTPUT.txt'
 f = open (output_file, 'wb')
 csv.writer(f).writerows(records)

This also adds a lot of spaces to the end of each outputted value. How would I get rid of these?

I'm fairly new to Python so any guidance would be gratefully received!

The problem is that you are using slicing:

>>> L = [1,2,3,4,5,6,7,8,9,10]
>>> L[7]
8
>>> L[7:8]  #NOTE: it's a *list* of a single element!
[8]

To replace spaces in rec[7] do:

records = [[rec[7].replace(' ', '')] + rec[9:12] + rec[3:4] for rec in records]
 records = [rec[7].replace(' ', '') + rec[9:12] + rec[3:4] for rec in records]

Python documentation wrote: str.replace(old, new[, count]) Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. This example demonstrate it:

In [13]: a ="AB09CDE"

In [14]: a.replace(" ", "")
Out[14]: 'AB09CDE'

In [15]: print a
AB09CDE

So, if rec is string field, then:

records = [rec.replace(" ", "") for rec in records]

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