Python草垛与需求

2024-10-01 17:24:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力让这个代码生效。当用户输入“qwqwqw”和b“qw”时,我需要它输出“3”而不是“2”,就像现在一样。它可能分别读取q和w,但我需要它来搜索b中用户输入的确切短语或字母。我需要它从a进行搜索。我如何才能更改代码以使其工作。我已经走了这么远,没有任何想法去改变。。。我不能使用任何文本比较方法,比如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))

Tags: 方法代码用户in文本inputlenif
1条回答
网友
1楼 · 发布于 2024-10-01 17:24:16
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

相关问题 更多 >

    热门问题