📌  相关文章
📜  Python – 用 i 替换辅音,用 j 替换元音

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

Python – 用 i 替换辅音,用 j 替换元音

给定一个字符串,用 i 替换所有元音,用 j 替换所有辅音。

方法 #1:使用 sub() + 正则表达式

在此,我们使用函数并为辅音和元音传递正则表达式来执行适当的替换。

Python3
# Python3 code to demonstrate working of
# Replace Consonants by i, Vowels by j
# Using Using sub() + regex
import re
 
# initializing strings
test_str = 'geeksforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing i, j
i, j = "V", "C"
 
# the negation of vowel regex is a consonant, denoted by "^"
res = re.sub("[^aeiouAEIOU]", j, test_str)
res = re.sub("[aeiouAEIOU]", i, res)
 
# printing result
print("The string after required replacement : " + str(res))


Python3
# Python3 code to demonstrate working of
# Replace Consonants by i, Vowels by j
# Using maketrans() + symmetric difference
import string
 
# initializing strings
test_str = 'geeksforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing i, j
i, j = "V", "C"
 
# extracting voweks and consonants
Vows = 'aeiouAEIOU'
 
# using sym. diff to get consonants
Cons = ''.join(set(string.ascii_letters).difference(set(Vows)))
 
# initializing translation
translation = str.maketrans(Vows + Cons, i * len(Vows) + j * len(Cons))
 
res = test_str.translate(translation)
 
# printing result
print("The string after required replacement : " + str(res))


输出
The original string is : geeksforgeeks
The string after required replacement : CVVCCCVCCVVCC

方法 #2:使用 maketrans() + 对称差分

在此,我们首先使用元音的对称差异来获取辅音,而 maketrans 是用于执行字符串替换任务的函数。

Python3

# Python3 code to demonstrate working of
# Replace Consonants by i, Vowels by j
# Using maketrans() + symmetric difference
import string
 
# initializing strings
test_str = 'geeksforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing i, j
i, j = "V", "C"
 
# extracting voweks and consonants
Vows = 'aeiouAEIOU'
 
# using sym. diff to get consonants
Cons = ''.join(set(string.ascii_letters).difference(set(Vows)))
 
# initializing translation
translation = str.maketrans(Vows + Cons, i * len(Vows) + j * len(Cons))
 
res = test_str.translate(translation)
 
# printing result
print("The string after required replacement : " + str(res))
输出
The original string is : geeksforgeeks
The string after required replacement : CVVCCCVCCVVCC