如何在特定ord中搜索字符串中的项目

2024-03-28 18:54:48 发布

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

我在处理一些问题,最近我遇到了一个问题。我有一个类似'hoouseeqwehouusseee'的字符串。我必须计算第一个单词'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)

Tags: 字符串答案in列表forif字母item
3条回答

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

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

我想出了一个解决办法,希望它能真正做到你在问题上的本意。你知道吗

代码:-

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))

希望对你有帮助。你知道吗

最简单的方法是使用正则表达式。你知道吗

  1. 首先我们在字符串中找到所有匹配项。你知道吗
  2. 然后我们计算一场比赛结束和下一场比赛开始之间的差值。你知道吗

以下是代码:

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]'

希望有帮助。你知道吗

相关问题 更多 >