Python|字符串中的交替元音和辅音
有时,在Python中使用字符串时,我们可能会遇到一个问题,即我们可能需要重组字符串,在其中添加替代元音和辅音。这是一个流行的学校级问题,解决这个问题可能很有用。让我们讨论一些可以解决这个问题的方法。
方法 #1:使用循环 + join() + zip_longest()
上述功能的组合可用于执行此任务。在此,我们首先在单独的列表中分离元音和辅音。然后使用 zip_longest() 和 join() 交替加入。
Python3
# Python3 code to demonstrate working of
# Alternate vowels and consonants in String
# using zip_longest() + join() + loop
from itertools import zip_longest
# initializing string
test_str = "gaeifgsbou"
# printing original string
print("The original string is : " + test_str)
# Alternate vowels and consonants in String
# using zip_longest() + join() + loop
vowels = ['a', 'e', 'i', 'o', 'u']
test_vow = []
test_con = []
for ele in test_str:
if ele in vowels:
test_vow.append(ele)
elif ele not in vowels:
test_con.append(ele)
res = ''.join(''.join(ele) for ele in zip_longest(test_vow, test_con, fillvalue =''))
# printing result
print("Alternate consonants vowels are: " + res)
Python3
# Python3 code to demonstrate working of
# Alternate vowels and consonants in String
# using loop + map() + lambda
from itertools import zip_longest
# initializing string
test_str = "gaeifgsbou"
# printing original string
print("The original string is : " + test_str)
# Alternate vowels and consonants in String
# using loop + map() + lambda
vowels = ['a', 'e', 'i', 'o', 'u']
test_vow = []
test_con = []
for ele in test_str:
if ele in vowels:
test_vow.append(ele)
elif ele not in vowels:
test_con.append(ele)
res = ''.join(map(lambda sub: sub[0] + sub[1],
zip_longest(test_vow, test_con, fillvalue ='')))
# printing result
print("Alternate consonants vowels are: " + res)
方法 #2:使用循环 + map() + lambda
也可以使用上述功能的组合来执行此任务。它与上述方法类似,唯一的区别是使用 map() 和 lambda 函数来执行交替连接。
Python3
# Python3 code to demonstrate working of
# Alternate vowels and consonants in String
# using loop + map() + lambda
from itertools import zip_longest
# initializing string
test_str = "gaeifgsbou"
# printing original string
print("The original string is : " + test_str)
# Alternate vowels and consonants in String
# using loop + map() + lambda
vowels = ['a', 'e', 'i', 'o', 'u']
test_vow = []
test_con = []
for ele in test_str:
if ele in vowels:
test_vow.append(ele)
elif ele not in vowels:
test_con.append(ele)
res = ''.join(map(lambda sub: sub[0] + sub[1],
zip_longest(test_vow, test_con, fillvalue ='')))
# printing result
print("Alternate consonants vowels are: " + res)
一种