Python 2.7 和正则表达式 : False if statement returns

标签 python regex python-2.7

为了练习正则表达式,我正在尝试创建一个非常简单的基于文本的游戏,类似于 Zork。但是我似乎无法让代码使用正则表达式工作。

运动.py

import re

def userMove():
    userInput = raw_input('Which direction do you want to move?')
    textArray = userInput.split()
    analyse = [v for v in textArray if re.search('north|east|south|west|^[NESW]', v, re.IGNORECASE)]

   print textArray
   print analyse

   movement = 'null'
   for string in analyse:
       if string is 'North' or 'n':
          movement = 'North'
       elif string is 'East'or'e':
          movement = 'East'
       elif string is 'South'or's':
          movement = 'South'
       elif string is 'West'or'w':
          movement = 'West'

print movement

if/elif 样本运行

>>> import movement
>>> moves = movement.userMove()
Which direction do you want to move?Lets walk East
['Lets', 'walk', 'East']
['East']
North

如果样本运行

>>> import movement
>>> moves = movement.userMove()
Which direction do you want to move?I`ll run North
['I`ll', 'run', 'North']
['North']
West

如果 for 循环不断地将 movement 设置为 North;并使用 if 语句而不是 elif 会将其设置为 West。 使正则表达式使用 userInput 代替 textArray 会导致该方法将 movement 保持为 null。

编辑 在进一步测试和更改代码后,我确信正则表达式没有问题,它是 if 语句或 for 循环的错误。

最佳答案

您的问题在于这些 if 语句:

if string is 'North' or 'n':
    movement = 'North'
elif string is 'East'or'e':
    movement = 'East'
elif string is 'South'or's':
    movement = 'South'
etc...

它们并不像您期望的那样有效。首先,您不应该将字符串与 is 进行比较 - 您应该使用 ==。其次,声明的评估更像是:

if (string is 'North') or 'n':
    movement = 'North'

因此,'n' 始终是 True - 这意味着您的 movement 变量始终设置为 North

试试这个:

if string in ('North', 'n'):
    etc...

关于Python 2.7 和正则表达式 : False if statement returns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19756500/

相关文章:

python - 我可以有条件地使用 pandas read_csv 转换器吗?

.net - 将 PHP 正则表达式转换为 .NET

php - 我的 preg_match 语法有效吗?

python - IOError : [Errno 13]

Python/Pandas - 用另一个数据框中的值替换一个数据框中的元素

jquery .load 与 python flask

python - 比较不同长度的 Pandas 数据帧

Python如何在一行中打印字典?

python - 交互 ipywidget 最小值和最大值

php - 带点和逗号的正则表达式货币格式