字符串中索引字符的Python测试值

2024-04-24 22:24:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码(这是完整的源代码):

testString = 'hello'
one = testString[0]
print one
if one == 'h'
    print "all is good"
else
    print "an error was encountered"
raw_input()

我在这里得到的错误如下: “文件”,第1行 如果其中一个=='h' ^ 语法错误:无效语法

我想做的是运行变量'one'通过一个测试,以确定它的值,即如果one=a运行functa,elif one=b等。我遇到的问题是,我根本无法运行这样的测试(即one=a),因为某种原因-控制台只是打开和关闭,提示一个错误。如何根据字符串测试这个变量的值(我认为它可能不是字符串)?你知道吗

我正在用Notepad++写这个并运行.py

编辑: 我尝试在控制台中运行它,但出现以下错误: errors encountered


Tags: 字符串代码anhelloif源代码is错误
3条回答

你可以这样做(你所缺少的只是一个冒号):

if one == "h": print "one is good."

如果有一组函数用于一个函数的不同值,则可能希望使用如下查找表:

# A table of functions to be called depending on the value of `one`
functions = {
    'a': functionA,
    'b': functionB,
    # etc.
}

# lookup the function for one in the table, 
# or set function to None is a matching function is not found.
function = functions.get(one, None)
if function is not None:
    # call the desired function
    function()
else:
    # There is no function for the value of one
    # Handle this case in some way (maybe raise an exception)

下面是一个你想要做的例子:

testString = 'hello'
one = testString[0]
two = testString[1]
three = testString[2]
four = testString[3]
five = testString[4]
pi = 3.14159

def isH():
    print "Letter is h"

def isE():
    print "Letter is e"

def isL():
    print "Letter is l"

def isO():
    print "Letter is o"

def test(myVar):
    if myVar == 'h' or myVar == 'H':
        isH()
    elif myVar == 'e' or myVar == 'E':
        isE()
    elif myVar == 'l' or myVar == 'L':
        isL()
    elif myVar == 'o' or myVar == 'O':
        isO()
    else:
        print "Unrecognized variable" 


test(one)
test(two)
test(three)
test(four)
test(five)
test(pi)

运行上述代码会产生:

Letter is h
Letter is e
Letter is l
Letter is l
Letter is o
Unrecognized variable

Python的妙处在于,不同类型的变量常常可以相互比较。你知道吗

例如:

x == '2' # Returns False
[1, 2, 3] == (1, 2, 3) # Returns False

正如Tolli所建议的,您可以将函数存储在字典中以帮助简化代码。你知道吗

根据你发布的图片,你收到的错误是无效的语法行

if one == 'h' print 'good'

应该是的

if one == 'h':
    print 'good'

你需要一个结肠,缩进很重要。你知道吗

旁白

顺便说一句,Python允许在一行中写这个,但是需要冒号。你知道吗

if one == 'h': print 'good'

但事实上,这一行版本是非常罕见的,根本不建议。你知道吗

相关问题 更多 >