How do I find out if one string is in another string in Python?

This question already has an answer here:

  • Does Python have a string 'contains' substring method? 13 answers

  • For finding one string in another, you may want to try the string find method.

    if b.find(a) != -1:  # -1 will be returned when a is not in b
        do_whatever
    

    To ignore capitalizations, you may want to do something like:

    if b.lower().find(a.lower()) != -1:
        do_whatever
    

    Additional commentary: As I type this, it's going on three years since I originally supplied this answer. The answer still gets occasional votes, both up and down. Since the answer works, presumably the down voters think this isn't as Pythonic as the if a in b: answer. As the comments state, that answer can fail silently if a and b aren't strings. There has been debate about whether that should be a concern. I've been around a while and have seen all sorts of things tried when code is re-used or the input data isn't what was expected. Thus, my viewpoint is that it shouldn't be assumed that the data will conform to expectations. Also, I believe the Zen of Python supports the viewpoint that this answer is more Pythonic:

    >>> import this
    The Zen of Python, by Tim Peters
    
    Beautiful is better than ugly.
    Explicit is better than implicit.
    ...
    Errors should never pass silently.
    Unless explicitly silenced.
    ....

    How about

    if a in b:
        print "a is in b"
    

    If you also want to ignore capitals:

    if a.lower() in b.lower():
        print "a is in b"
    

    if a in b:
        # insert code here
    
    链接地址: http://www.djcxy.com/p/9378.html

    上一篇: 检查一个字符串是否有2个字符相邻

    下一篇: 如何找出一个字符串是否在Python的另一个字符串中?