简体   繁体   English

检查字符串是否包含 set 中的任何字符

[英]check if a string contains any char from set

Actually, i'm working on a task from SPOJ.实际上,我正在处理 SPOJ 的一项任务。 How to check if a string contains any char from set, but first char from string where a char from set occur can not be deleted.如何检查字符串是否包含集合中的任何字符,但无法删除出现集合中字符的字符串中的第一个字符。

Fe Have a string Fe 有一个字符串

word = "anAconda_elEphant"

and a set of vowels:和一组元音:

vowels = set('aeiouyAEIOUY')

I want in result a string我想要一个字符串

word = "ancnd_lphnt"

This should return True when occurence of any char in set is equal 1. I know that argument for a method .count() must be str, not set.当集合中任何字符的出现等于 1 时,这应该返回 True。我知道方法.count() 的参数必须是 str,而不是 set。

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

just use a regular expression只需使用正则表达式

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'

as mentioned if you expect it to skip the first match of the set as opposed to just the first letter you will need a different solution如前所述,如果您希望它跳过集合的第一个匹配项而不是第一个字母,那么您将需要不同的解决方案

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

the easiest is to split it into two steps first split the string on the first match最简单的方法是将其拆分为两步,首先在第一次匹配时拆分字符串

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"

You can use a for loop as below.您可以使用for循环,如下所示。 The idea is to build a list, and use a flag to mark when you meet a character from vowels .这个想法是建立一个列表,并在遇到来自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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM