📜  Python|字符串中的元音索引

📅  最后修改于: 2022-05-13 01:54:20.497000             🧑  作者: Mango

Python|字符串中的元音索引

有时,在使用Python字符串时,我们可能会遇到需要提取其中元音索引的问题。这种应用程序在日常编程中很常见。让我们讨论可以执行此任务的某些方式。

方法#1:使用循环
这是可以执行此任务的一种方式。在此,我们使用蛮力来执行此任务。在此我们迭代每个字符串元素并测试元音。

# Python3 code to demonstrate working of 
# Vowel indices in String
# Using loop
  
# initializing string
test_str = "geeksforgeeks"
  
# printing original string
print("The original string is : " + test_str)
  
# Vowel indices in String
# Using loop
res = []
for ele in range(len(test_str)):
    if test_str[ele] in "aeiou":
       res.append(ele)
  
# printing result 
print("The vowel indices are : " + str(res)) 
输出 :
The original string is : geeksforgeeks
The vowel indices are : [1, 2, 6, 9, 10]

方法 #2:使用enumerate() + 列表推导
上述方法的组合也可用于执行此任务。在此,我们使用 enumerate() 访问索引,并使用列表推导来检查元音。

# Python3 code to demonstrate working of 
# Vowel indices in String
# Using list comprehension + enumerate()
  
# initializing string
test_str = "geeksforgeeks"
  
# printing original string
print("The original string is : " + test_str)
  
# Vowel indices in String
# Using list comprehension + enumerate()
res = [idx for idx, ele in enumerate(test_str) if ele in "aeiou"]
  
# printing result 
print("The vowel indices are : " + str(res)) 
输出 :
The original string is : geeksforgeeks
The vowel indices are : [1, 2, 6, 9, 10]