我在使用以下代码时遇到了一些问题:
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
我遇到的问题是它将换行符读为字符;所以我在输出上得到了这个 -
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
如何让它忽略换行'字符'?
答案 0 :(得分:5)
更改此行:
for character in line.rstrip():
你也可以使if / else结构更平坦:
with open('townhall.map', 'r') as f:
for line in f:
for character in line.rstrip():
if character == "x":
print "WALL"
elif character == "a":
print "LAND"
else:
print "Unexpected Error loading map!"
或将打印定义为字典:
char = {'x': 'WALL',
'a': 'LAND'}
with open('townhall.map', 'r') as f:
for line in f:
for character in line.rstrip():
try:
print char[character]
except KeyError:
print "Unexpected Error loading map!"
答案 1 :(得分:1)
有很多方法可以做到这一点。其中之一是:
with open('townhall.map', 'r') as f:
for line in f:
for character in line:
if character in ['x','a']:
if character == "x":
print "WALL"
else:
if character == "a":
print "LAND"
答案 2 :(得分:1)
您还需要考虑换行符,并忽略它。
with open('townhall.map', 'r') as f:
for line in f:
for character in line:
if character == "x":
print "WALL"
elif character == "a":
print "LAND"
elif character == "\n":
pass
else:
print "Unexpected Error loading map!"