Python 匹配字符串中每个单词的第一个元音,并用正则表达式逗号分隔打印它们?
这是我到目前为止所拥有的Python 匹配字符串中每个单词的第一个元音,并用正则表达式逗号分隔打印它们?,python,regex,string,findall,Python,Regex,String,Findall,这是我到目前为止所拥有的 my_str = "The sky's the limit" regex = re.findall(r"\b\w*?[aeiouAEIOU]", my_str) joined_str = ", ".join(regex) print(joined_str) 我想把它打印出来 e, e, i 但它会打印出来 The, the, li 那么,如何忽略带元音的单词前面的字符,只打印每个单词的第一个元音,并用逗号分隔元音呢?您只需要通过将表达式封装在捕获组中来限制要返
my_str = "The sky's the limit"
regex = re.findall(r"\b\w*?[aeiouAEIOU]", my_str)
joined_str = ", ".join(regex)
print(joined_str)
我想把它打印出来
e, e, i
但它会打印出来
The, the, li
那么,如何忽略带元音的单词前面的字符,只打印每个单词的第一个元音,并用逗号分隔元音呢?您只需要通过将表达式封装在捕获组中来限制要返回的部分:
>>> re.findall(r"\b\w*?([aeiouAEIOU])", my_str)
['e', 'e', 'i']
()
告诉正则表达式引擎只返回()
中表达式的匹配项。如果可以不使用正则表达式,则可以这样做,如下所示:
def find_first_vowel(s):
first_vowels = ''
for word in s.split():
for index, char in enumerate(word):
if char in 'aeiouAEIOU': # you can check the index here
first_vowels += char
break
return ', '.join(first_vowels)
my_str = "The sky's the limit"
>>> print(find_first_vowel(my_str))
e, e, i
谢谢伯翰!另一个问题,因为我不想用一个完全不同的主题来回答这些小问题中的另一个。如何使用re.sub()函数将字符串中所有出现的'the'和'the'替换为'a'。有没有办法阻止它匹配以“the”开头的其他单词?很抱歉没有指定此项是的,只需在其周围加上一个单词边界
re.sub(r'\b[T|T]he\b','a',my_str)