如何在使用乌龟的同时摆脱python3中的空白?

时间:2012-11-27 12:50:27

标签: python-3.2

如何删除python3中的空格?

我正在编写一个需要完成各种测试的程序。该程序使用乌龟,基本上用户输入各种命令,程序需要运行乌龟来完成它们。其中一个测试看起来像这样:

forward 200
right 90
forward 400
right 90
forward 100
right 90
forward 400
right 90
forward 100

最后两行是空格,到目前为止我的程序可以运行它们但是当它到达空白时它会崩溃。如何让python去除这个空格,我应该把它放在我的代码中?感谢

1 个答案:

答案 0 :(得分:0)

我不确定你的说明是如何存储的,所以我会给你一个我最可能的假设的答案。

这是一个列表

这是最简单的...使用列表理解来摆脱完全由空格组成的任何指令

instruction_list = [instruction.strip() for instruction in instruction_list if instruction.strip()]

这是一个带有换行符的大字符串

instruction_list = instruction_string.split('\n') #make a list
instruction_list = [instruction.strip() for instruction in instruction_list if instruction.strip()] #process list as before
instruction_string = '\n'.join(instruction_list) #reconstruct string

这是一个文件

for line in instruction_file:
    if not line.strip(): #if the line is made up entirely of whitespace
        continue         #skip to the next loop iteration
    process_instruction(line)