I’m having some problems with the following code:
with open('townhall.map', 'r') as f:
for line in f:
for character in line:
if character == "x":
print "WALL"
else:
if character == "a":
print "LAND"
else:
print "Unexpected Error loading map!"
townhall.map:
xxxxx
xaaax
xaaax
xaaax
xxxxx
The problem I have is that it reads the newlines as characters; so I get this on output –
WALL
WALL
WALL
WALL
WALL
Unexpected Error loading map!
WALL
LAND
LAND
LAND
WALL
Unexpected Error loading map!
WALL
LAND
LAND
LAND
WALL
Unexpected Error loading map!
WALL
LAND
LAND
LAND
WALL
Unexpected Error loading map!
WALL
WALL
WALL
WALL
WALL
How do I make it ignore newline ‘characters’?
Change this line:
And you can also make the if/else structure flatter:
or define the printing as a dictionary: