找到' Y'的出现?或者' N'在一个字符串中

时间:2016-03-19 05:21:34

标签: python string printing comparison

如何才能使两个字符串正确比较?如果字符串Answers中包含'N',那么会有输出吗?

def stringSearcher():             #Seperates and returns 2 strings from .txt file
    f = open("QuestionTree.txt", "r")
    currentLine = f.readline()
    for line in f:
        if Answer in line: 
            yesnos, answerOrQuestion = line.split(',')
            return answerOrQuestion, yesnos

while True:

    Answer = raw_input("Y or N: ")              #User input
    answerOrQuestion, yesnos = stringSearcher() #allows usage of Return variables

    if yesnos == Answer:     #Will compare the 'Y' in string but not 
        print answerOrQuestion

这是输出的样子:

Y or N: N    #Not print the N in the text file
Y or N: Y 
In the Towers?

Y or N: YN
Y or N: YY
Old Tower?

Y or N: YYY
7 floors tall?

Y or N: ^CTraceback (most recent call last):
  File "TestCode.py", line 11, in <module>
    Answer = raw_input("Y or N: ")

这就是文本文件的样子:

,这是宿舍吗? Y,在塔楼? YY,老塔? YYY,7层高吗? YYYY,是Carey吗? YYYYY,Carey Hall YYYYN,特劳特曼大厅 YYYN,是惠勒吗? N,西部的使命? 纽约,布鲁姆菲尔德的S? NYY,CMU拥有? NYYY,Kewadin NYYN,B-Ball Court? NYYNY,是列克星敦吗?

2 个答案:

答案 0 :(得分:1)

更改

def stringSearcher(): 

def stringSearcher(Answer): 

答案 1 :(得分:0)

import re

def stringSearcher(Answer):
    f = open("QuestionTree.txt", "r")
    currentLine = f.readline()
    for line in f:
        if re.match(Answer, line): 
            yesnos, answerOrQuestion = line.split(',')
            return answerOrQuestion, yesnos

while True:

    Answer = raw_input("Y or N: ")
    answerOrQuestion, yesnos = stringSearcher(Answer)

    if Answer == yesnos:     #Will compare the 'Y' in string but not 
        print answerOrQuestion