Python 如何按特定顺序搜索字符串中的项目

Python 如何按特定顺序搜索字符串中的项目,python,Python,我正在解决一些问题,最近我遇到了一个问题。我有一个类似于'hoouseeqwehousseee'的字符串。我必须计算第一个单词'house'和另一个单词'house'之间的字符数。对于上述示例,额外的字母是:'e','q','w','e',因此答案是4。我试图将字符串转换为列表,但不知道如何继续 word = list(word) x = [] for item in word: if item not in x: x.append(item) print(x) 收款台

我正在解决一些问题,最近我遇到了一个问题。我有一个类似于
'hoouseeqwehousseee'
的字符串。我必须计算第一个单词
'house'
和另一个单词
'house'
之间的字符数。对于上述示例,额外的字母是:
'e'
'q'
'w'
'e'
,因此答案是
4
。我试图将字符串转换为列表,但不知道如何继续

word = list(word)
x = []
for item in word:
    if item not in x:
        x.append(item)
print(x)

收款台将帮助您:


由于您的需求不明确,这可能无法解决您的确切问题,但它应该给您一个开始。这将返回匹配
h+o+u+s+e
regex的字符串的第一个和第二个实例之间的字母数

import re

s = 'hoouseeqwehouusseee'

def length_of_first_gap(test_string, word):
    pattern = '+'.join(list(word))
    return len(re.split(pattern, test_string)[1])

>>> length_of_first_gap(s, 'house')
>>> 4

最简单的方法是使用正则表达式

  • 首先,我们在字符串中找到所有匹配项
  • 然后我们计算一场比赛结束和下一场比赛开始之间的差值
  • 下面是一个代码:

    import re
    string = 'hoouseeqwehouusseee'
    word = 'house'
    
    pattern = '+'.join(word)
    list_of_word_indices = [(match.start(0), match.end(0)) for match in re.finditer(pattern, string)]
    list_of_gap_lengthes = [list_of_word_indices[i+1][0] - list_of_word_indices[i][1]
                            for i in range(len(list_of_word_indices)-1)] 
    
    print(list_of_gap_lengthes)
    
    你将得到一个空白列表作为回报。在您的示例中,这是'[4]'


    希望这能有所帮助。

    我想出了一个解决方案,希望它能真正做到你在问题上的真正意图

    代码:-

    word = 'hoouseeqwehouusseee'
    def count_char(string):
        new_string1 = word.replace('hoouse','')
        new_string2 = new_string1.replace('houusseee','')
        return len(new_string2)
    
    print(count_char(word))
    

    希望它能帮助您。

    您的字符串中不会出现“house”
    。您有
    'hoousee'
    我知道,但无助于解决问题。你的问题也不能帮助我们回答你。你真的需要澄清你的问题。(a)你需要更加清楚你的要求,因为房子这个词从来没有出现过。打字错误如果不是,那么你需要解释。(b) 为什么(确切地说为什么)你想创建一个列表,你希望最终的列表是什么样子?@Dante不,这并不清楚,只是重复而已yourself@PM2Ring,否,因为“house”序列在第一个“e”之后结束,这更接近于注释而不是答案。如果我使用print(第一个间隔的长度('footbaallleqeqwfootbaaall','footbaall','footbaall')它将只显示5而不是8。它应该在给定单词的结尾或结尾处计算额外的字母。在这里,它应该计算'llleqew',两个尾随的
    l
    s使它变得模棱两可。第一个间隔的长度应该是多少('aaaaaaaaaaaa',aa)return?仅返回0,因为“aa”之间没有其他字母,因此这将为您提供间隙长度的列表。如果您有3个“house”实例,则代码将返回2个距离的列表。对于“hoouseewerhousseaaahouse”,您将有[5,3],对于“hoouseewerhousse”,您将有[5]
    word = 'hoouseeqwehouusseee'
    def count_char(string):
        new_string1 = word.replace('hoouse','')
        new_string2 = new_string1.replace('houusseee','')
        return len(new_string2)
    
    print(count_char(word))