Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

python - How to?: If string contains uppercase ''X'' print("X spotted!")

I'm working on a school assignment and it works (so far) but I don't understand why I had to put the second if statement after else in the tester function for that if p condition (Xavier) to work.

  1. I need someone to explain why I couldn't use the if before else in this case.

  2. The same condition. It actually needs to test if the user input contains an uppercase X. I have searched online but just can't figure out which method to use.

     def tester(p, givenstring = "Too short"):    
         result=len(p)
         if result>=10:
             print(p)
         else:
             print(givenstring)
         if p == "Is Xavier here?":  # if p == "X" doesn't work.
             print("X is spotted!")
    
     def main():
         while True:
             prompt=input("Write something (quit ends): ")
             if prompt=="quit":
                 break
             else:
                 tester(prompt)
    
     if __name__ == "__main__":
        main()
    
question from:https://stackoverflow.com/questions/65870595/how-to-if-string-contains-uppercase-x-printx-spotted

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
def tester(p, givenstring = "Too short"):    
    result=len(p)
    if result>=10:
        print(p)
    else:
        print(givenstring)
    #Comments should be created using hash(#) not (//) >> //if p == "X" doesn't work.
    if p == "Is Xavier here?":    # this is doing an exact match of the string and not finding 'X'          
        print("X is spotted!")
def tester(p, givenstring = "Too short"):    
    result=len(p)
    if result>=10:
        print(p)
    else:
        print(givenstring)
    if 'X' in p: # this will return True if 'X' is present in p
        print("X is spotted!")

def main():
    while True:
        prompt=input("Write something (quit ends): ")
        if prompt=="quit":
            break
        else:
            tester(prompt)
main()
Write something (quit ends): This is captain x-merica
This is captain x-merica
Write something (quit ends): This is captain X-merica
This is captain X-merica
X is spotted!
Write something (quit ends): quit

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...