python switch语句不起作用

use*_*014 -2 python file-io switch-statement

我找到了一个实现switch语句的函数 - >

File = open('/file.txt','r')

    String = File.readline()
    String = str(String)
    print String 

    for case in switch(String):
        if case("Head"):
            print "test successed"
            break
        if case("Small"):
            print String
            break
        if case("Big"):
            print String
            break  
        if case():
            print String 
            break 
Run Code Online (Sandbox Code Playgroud)

打印时的字符串值是Head,但是switch语句总是转到最后一种情况..函数显然工作正常,因为当我用v ="Head"更改字符串时它工作了!!!

知道出了什么问题吗?

开关功能 - >

class switch(object):
 def __init__(self, value):
    self.value = value
    self.fall = False

 def __iter__(self):
    """Return the match method once, then stop"""
    yield self.match
    raise StopIteration

 def match(self, *args):
    """Indicate whether or not to enter a case suite"""
    if self.fall or not args:
        return True
    elif self.value in args: # changed for v1.5, see below
        self.fall = True
        return True
    else:
        return False
Run Code Online (Sandbox Code Playgroud)

Chr*_*gan 5

请不要写这样的代码.以适当的Python风格做到这一点.它容易阅读.任何遇到"切换"混乱的人都可能会痛苦地诅咒你.

with open('/file.txt', 'r') as fp:
    line = fp.readline().rstrip('\n')
    print line

if line == 'Head':
    print "test successed"
elif line == 'Small':
    print line
elif line == 'Big':
    print line
else:
    print line
Run Code Online (Sandbox Code Playgroud)

至于为什么它失败了,这个readline()调用很可能包括一个尾随的换行符,和'Head' != 'Head\n'.