📜  Python – 用下一个元音替换元音

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

Python – 用下一个元音替换元音

给定一个字符串,用系列中的下一个元音替换每个元音。

方法 #1:使用 zip() + 列表理解

这是可以执行此任务的方式之一。在此我们使用 zip() 执行形成替换字典的任务,然后使用列表推导执行替换下一个元音的任务。

Python3
# Python3 code to demonstrate working of 
# Replace vowels by next vowel
# Using list comprehension + zip()
  
# initializing string
test_str = 'geekforgeeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# constructing dictionary using zip()
vow = 'a e i o u'.split()
temp = dict(zip(vow, vow[1:] + [vow[0]]))
  
# list comprehension to perform replacement
res = "".join([temp.get(ele, ele) for ele in test_str])
  
# printing result 
print("The replaced string : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Replace vowels by next vowel
# Using list comprehension + dictionary comprehension
  
# initializing string
test_str = 'geekforgeeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# constructing dictionary using dictionary comprehension
vow = "aeiou"
temp = {vow[idx] : vow[(idx + 1) % len(vow)] for idx in range(len(vow))}
  
# using get() to map elements to dictionary and join to convert
res = "".join([temp.get(ele, ele) for ele in test_str])
  
# printing result 
print("The replaced string : " + str(res))


输出
The original string is : geekforgeeks
The replaced string : giikfurgiiks

方法#2:使用字典理解+列表理解

这是可以执行此任务的另一种方式。在此,我们使用字典推导执行映射任务,列表推导用于执行替换任务。

Python3

# Python3 code to demonstrate working of 
# Replace vowels by next vowel
# Using list comprehension + dictionary comprehension
  
# initializing string
test_str = 'geekforgeeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# constructing dictionary using dictionary comprehension
vow = "aeiou"
temp = {vow[idx] : vow[(idx + 1) % len(vow)] for idx in range(len(vow))}
  
# using get() to map elements to dictionary and join to convert
res = "".join([temp.get(ele, ele) for ele in test_str])
  
# printing result 
print("The replaced string : " + str(res)) 
输出
The original string is : geekforgeeks
The replaced string : giikfurgiiks