检查字符串是否包含来自s的任何字符

2024-09-19 23:38:48 发布

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

实际上,我在执行斯波吉的任务。如何检查字符串是否包含集合中的任何字符,但不能删除出现集合中字符的字符串中的第一个字符。你知道吗

F.e。 有一根绳子

word = "anAconda_elEphant"

以及一组元音:

vowels = set('aeiouyAEIOUY')

我想要一个字符串

word = "ancnd_lphnt"

当集合中任何字符的出现次数等于1时,该值应返回True。我知道方法.count()的参数必须是str,而不是set。你知道吗

if word.count(vowels) == 1:
   for char in word[char_pos:]:
        if char in vowels:
            char.replace('')

Tags: 字符串inifcountanaconda字符word元音
3条回答

只需使用正则表达式

import re
word = "anAconda_elEphant"
# use a  "lookbehind" to make sure there is at least one character in front of this character...
print(re.sub("(?<=.)[aeiouyAEIOUY]",'',word))
# 'ancnd_lphnt'

如前所述,如果您希望它跳过集合的第一个匹配,而不是仅仅跳过第一个字母,您将需要一个不同的解决方案

print(re.sub("(?<=.)[aeiouyAEIOUY]",'',"bace"))
# 'bc' # a is not the FIRST letter so it is replaced

最简单的方法是把它分成两个步骤 在第一场比赛中先把绳子分开

word = "bace"
splitted_string = re.split("(.*?[aeiouyAEIOUY])",word,1)
# you will notice we have an extra empty string at the beginning of our matches ... so we can skip that
lhs,rhs = splitted_string[1:]
# now just run a simple re.sub on our rhs and rejoin the halves
print(lhs + re.sub("[aeiouyAEIOUY]",'',rhs))
# results in "bac"

您可以使用for循环,如下所示。其思想是构建一个列表,并在遇到来自vowels的字符时使用标志进行标记。你知道吗

word = "anAconda_elEphant"
vowels = set('aeiouyAEIOUY')

flag = False

L = []
for ch in word:
    if (ch not in vowels) or (not flag):
        L.append(ch)
    if ch in vowels:
        flag = True

word = ''.join(L)

print(word)

ancnd_lphnt

相关问题 更多 >