Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Removing spaces and '\n' from list

Tags:

python

list

I'm trying to delete white spaces and enter's from a list, which i need to import as coordinates. However this does not seem to work. giving the following error:

AttributeError: 'list' object has no attribute 'strip'

Currently i'm still looking into the removal of the spaces (first these have to be deleted, then the enter's will follow).

Does anyone has any suggestions why this does not work?

the code is as follow:

# Open a file
Bronbestand = open("D:\\Documents\\SkyDrive\\afstuderen\\99 EEM - Abaqus 6.11.2\\scripting\\testuitlezen4.txt", "r")
headerLine = Bronbestand.readline()
valueList = headerLine.split(",")
#valueList = valueList.replace(" ","")

xValueIndex = valueList.index("x")
yValueIndex = valueList.index("y")
#xValueIndex = xValueIndex.replace(" ","")
#yValueIndex = yValueIndex.replace(" ","")

coordList = []

for line in Bronbestand.readlines():
    segmentedLine = line.split(",")
    coordList.append([segmentedLine[xValueIndex], segmentedLine[yValueIndex]])

coordList2 = [x.strip(' ') for x in coordList]

print coordList2

Where the "Bronbestand" is the following:

id,x,y,
      1,  -1.24344945,   4.84291601
      2,  -2.40876842,   4.38153362
      3,  -3.42273545,    3.6448431
      4,  -4.22163963,   2.67913389
      5,   -4.7552824,   1.54508495
      6,  -4.99013376, -0.313952595
      7,   -4.7552824,  -1.54508495
      8,  -4.22163963,  -2.67913389
      9,  -3.42273545,   -3.6448431

Thank you all in advance for the help!

like image 529
user1967364 Avatar asked May 09 '26 16:05

user1967364


2 Answers

It looks like your problem is here. The append() method adds a single item to the list. If you append a list to a list, you get a list of lists.

coordList.append([segmentedLine[xValueIndex], segmentedLine[yValueIndex]])

There are two ways to fix this.

# Append separately
coordList.append(segmentedLine[xValueIndex])
coordList.append(segmentedLine[yValueIndex])

# Use extend()
coordList.extend([segmentedLine[xValueIndex], segmentedLine[yValueIndex]])

Alternatively, if you meant to have a list of lists, you'll need to iterate two levels deep.

coordList2 = [[x.strip(' ') for x in y] for y in coordList]
like image 110
Dietrich Epp Avatar answered May 12 '26 05:05

Dietrich Epp


import csv
buff = csv.DictReader(Bronbestand)

result = []

for item in buff:
    result.append(dict([(key, item[key].strip()]) for key in item if key])) # {'y': '-3.6448431', 'x': '-3.42273545', 'id': '9'}

your data is valid Comma seperated Values (CSV) try to use the native python csv parser.

like image 32
MBarsi Avatar answered May 12 '26 04:05

MBarsi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!