2014-11-04 80 views
0

我想比較一個輸入字符串,但是當我輸入barack作爲輸入時,編譯器直接轉到其他條件,忽略if條件並給我輸出「Wrong答案「比較字符串與輸入字符串:: python

def main(): 
    First_name = raw_input(" enter the first name of President Obama : ") #input 
    if First_name == ['b', 'a', 'r','a', 'c', 'k'] : 
      print "Correct answer" 
     else : 
      print "Wrong answer" 


    Exit_key = input('Press any key to end') 
+2

你爲什麼認爲輸入是一個列表?! – jonrsharpe 2014-11-04 22:38:16

+0

Python字符串不是char數組。 – 2014-11-04 22:41:11

回答

2

你有這樣做的原因嗎?嘗試:

if First_name == "Barack" : 
+0

就像一個魅力工作謝謝 – johnny 2014-11-04 22:42:47

+0

'如果First_name.lower()== barack'會更pythonic – Hackaholic 2014-11-04 22:43:23

+0

沒問題,請標記爲接受的答案,如果它的工作。 – marsh 2014-11-04 22:46:03

1

raw_input是一個字符串,所以做你想要什麼,你將不得不呼籲字符串列表:

if list(First_name) == ['b', 'a', 'r','a', 'c', 'k']) 

這是比較容易只是做if First_name == "barack"

In [1]: inp = raw_input() 
barack 

In [2]: list(inp) 
Out[2]: ['b', 'a', 'r', 'a', 'c', 'k'] 

In [3]: inp 
Out[3]: 'barack' 
0

使用lambdamap。只是如果你想學習基本概念

if map(lambda x:x,First_name.lower()) == ['b', 'a', 'r','a', 'c', 'k']: