以下是一个使用Python编写的函数,将字符串中的辅音字母替换为"!"的示例代码:
def replace_consonants_with_exclamation(string):
vowels = ['a', 'e', 'i', 'o', 'u'] # 元音字母列表
result = ""
for char in string:
if char.lower() not in vowels and char.isalpha():
result += "!"
else:
result += char
return result
# 测试示例
input_str = "Hello World"
output_str = replace_consonants_with_exclamation(input_str)
print(output_str) # 输出: "H!ll! W!rld"
此函数中,我们首先定义了一个包含所有元音字母的列表。然后,我们遍历输入字符串中的每个字符。如果字符不是元音字母且是一个字母,则将其替换为"!",否则保持不变。最后,将替换完成的结果返回。