Python - Replace vowels in a string with a specific character K

Python - Replace vowels in a string with a specific character K

In this tutorial, we will explore how to replace each vowel in a given string with a specified character K.

Objective:

Given a string s and a character K, replace each vowel in s with the character K.

Sample Input:

Replace vowels in the word "apple" with the character "#":

s = "apple" K = "#" 

Expected Output:

"#ppl#" 

Tutorial:

Step 1: Define a set containing all the vowels.

vowels = set("aeiouAEIOU") 

Step 2: Iterate over each character in the string.

Step 3: If the character is a vowel (i.e., it exists in the vowels set), replace it with the character K. Otherwise, keep the character as it is.

Here's a function to achieve this:

def replace_vowels_with_char(s, K): vowels = set("aeiouAEIOU") return ''.join(K if char in vowels else char for char in s) 

Step 4: Test the function using the sample input.

s = "apple" K = "#" print(replace_vowels_with_char(s, K)) # Output: "#ppl#" 

Additional Points:

  1. Case Sensitivity: The provided solution works for both lowercase and uppercase vowels. If you only want to replace lowercase or uppercase vowels, you can adjust the vowels set accordingly.

  2. Performance: Using a set to check for vowels ensures that the solution is efficient since the set membership test is O(1).

Recap:

In this tutorial, we've learned how to replace each vowel in a string with a specific character K using a set to determine if a character is a vowel. This approach offers a simple and efficient way to replace characters in a string based on specific criteria.


More Tags

mobilecoreservices cython navigationview android-gps yaml asp-net-config-builders sendmail razor-2 fongo data-extraction

More Programming Guides

Other Guides

More Programming Examples