Python干草堆和针

时间:2016-05-22 09:46:06

标签: python

我正在尝试使用此代码。当用户输入“qwqwqw”和b“qw”时,我需要输出“3”而非“2”,就像现在一样。它可能分别读取q和w但我需要它来搜索b中的确切短语或字母用户输入。我需要它从一个搜索。我怎么能改变代码才能使它工作。我已经到了这么远,并且没有更多的想法要改变什么...而且我不能使用任何文本比较count或findall等方法。到目前为止,这是我的代码:

    a = input("String1: ")
    b = input("String2: ")

    common = {}
    if len(a)>len(b):
        for letter in a:
            if letter in b:
               common[letter]=1

   print (len(common))

1 个答案:

答案 0 :(得分:0)

foo = 'qwqwqw'
bar = 'wq'

idx = 0
counter = 0

while True:
    try:
        # find the next instance of bar, starting at idx
        found_at = foo.index(bar, idx)

        # move idx to the next possible position (after the instance of bar)
        idx = found_at + len(bar)

        # increase the counter
        counter += 1
    except ValueError:
        # foo.index(bar) will raise ValueError if bar cannot be found.  that
        # means we are done
        break

print counter