5 Best Ways to Check if a String Can Be Converted to Another by Replacing Vowels and Consonants in Python

Rate this post

πŸ’‘ Problem Formulation: We often face string manipulation challenges in programming. Specifically, the ability to determine if one string can be transformed into another by swapping vowels and consonants is a common task. For instance, converting “hello” into “holle” is achievable by swapping ‘e’ with ‘o’ but transforming “hello” into “hielo” is not.

Method 1: Character Mapping Approach

This method involves creating two dictionaries to map the vowel and consonant transformations from string A to string B. It checks for the presence of one-to-one character mapping for each class of characters (vowel or consonant) independently.

Here’s an example:

def can_transform(s1, s2):
    if len(s1) != len(s2):
        return False
    vowels = 'aeiou'
    vowel_map, consonant_map = {}, {}
    for c1, c2 in zip(s1, s2):
        if (c1 in vowels) != (c2 in vowels):  # Different classes
            return False
        if c1 in vowels:
            if c1 in vowel_map and vowel_map[c1] != c2:
                return False
            vowel_map[c1] = c2
            if c1 in consonant_map and consonant_map[c1] != c2:
                return False
            consonant_map[c1] = c2
    return True

print(can_transform("hello", "holle"))
print(can_transform("hello", "hielo"))



This code defines a function can_transform(s1, s2) which takes two strings and returns True if the first string can be transformed into the second by replacing vowels with vowels and consonants with consonants, else False. It uses two dictionaries to map the characters from the first string to the second and ensures that each vowel and consonant has a consistent replacement.

Method 2: Set Comparison

By leveraging set comparison, we can quickly ascertain if the two strings contain the same sets of vowels and consonants, which is a necessary condition for one being transformable into the other.

Here’s an example:

def has_same_char_sets(s1, s2):
    vowels_set = set('aeiou')
    s1_vowels = set(filter(lambda x: x in vowels_set, s1))
    s2_vowels = set(filter(lambda x: x in vowels_set, s2))

    s1_consonants = set(s1) - s1_vowels
    s2_consonants = set(s2) - s2_vowels

    return s1_vowels == s2_vowels and s1_consonants == s2_consonants

print(has_same_char_sets("hello", "holle"))
print(has_same_char_sets("hello", "hielo"))



The function has_same_char_sets(s1, s2) checks if the input strings s1 and s2 have the same sets of vowels and consonants. This is a quick way to determine if a transformation is possible but does not guarantee it, as it doesn’t account for the order or number of occurrences of the characters.

Method 3: Frequency Counter

This approach uses two dictionaries to count the frequency of the vowels and consonants separately in each string. If the frequency distributions match, one string can be transformed into the other.

Here’s an example:

from collections import Counter

def has_matching_frequencies(s1, s2):
    vowels = 'aeiou'

    def character_frequency(s, character_set):
        return Counter(filter(lambda x: x in character_set, s))

    return (character_frequency(s1, vowels) == character_frequency(s2, vowels) and
            character_frequency(s1, set(s1) - set(vowels)) == character_frequency(s2, set(s2) - set(vowels)))

print(has_matching_frequencies("hello", "holle"))
print(has_matching_frequencies("hello", "hielo"))



The function has_matching_frequencies(s1, s2) uses the Counter class from the collections module to count the vowels and consonants in each string. It then checks if the two strings have identical frequencies of vowels and consonants, indicating that a transformation is possible by swapping the letters accordingly.

Method 4: Regex Comparison

Regular expressions can be used to create patterns that match vowels and consonants in both strings, an essential prerequisite for identifying if a transformation is possible.

Here’s an example:

import re

def can_be_transformed_by_regex(s1, s2):
    vowel_regex = r"[aeiou]"
    # Replace vowels with 'V' and consonants with 'C'
    def replace_with_placeholders(s, regex, placeholder):
        return re.sub(regex, placeholder, s)

    s1_pattern = replace_with_placeholders(s1, vowel_regex, 'V')
    s1_pattern = replace_with_placeholders(s1_pattern, r"[^V]", 'C')

    s2_pattern = replace_with_placeholders(s2, vowel_regex, 'V')
    s2_pattern = replace_with_placeholders(s2_pattern, r"[^V]", 'C')

    return s1_pattern == s2_pattern

print(can_be_transformed_by_regex("hello", "holle"))
print(can_be_transformed_by_regex("hello", "hielo"))



The function can_be_transformed_by_regex(s1, s2) uses regular expressions to generate patterns from the input strings. Vowels are replaced with the placeholder ‘V’ and consonants with ‘C’. If the resulting patterns are the same, the strings can be transformed into each other.

Bonus One-Liner Method 5: Lambda and Sorted

This concise one-liner uses a lambda function to sort both strings by their vowels and consonants and compares their sorted versions, searching for a transformation possibility.

Here’s an example:

can_transform = lambda s1, s2: (sorted(filter(str.isalpha, s1.lower())), sorted(filter(str.isalpha, s2.lower())))

print(can_transform("hello", "holle"))
print(can_transform("hello", "hielo"))


(['e', 'h', 'l', 'l', 'o'], ['e', 'h', 'l', 'l', 'o'])
(['e', 'h', 'l', 'l', 'o'], ['e', 'h', 'i', 'l', 'o'])

This one-liner can_transform lambda function sorts the vowels and consonants found in the strings s1 and s2 in alphabetical order, to allow for quick comparison. However, it cannot differentiate between vowels and consonants, making it a less reliable method for transformation checks.


  • Method 1: Character Mapping Approach. Strengths: Exact transformation check. Weaknesses: Somewhat complex implementation.
  • Method 2: Set Comparison. Strengths: Fast preliminary check. Weaknesses: Does not confirm transformation, false positives possible.
  • Method 3: Frequency Counter. Strengths: Ensures accurate character counts. Weaknesses: More verbose and computationally intensive.
  • Method 4: Regex Comparison. Strengths: Pattern-based transformation verification. Weaknesses: Depends on understanding regex and placeholders.
  • Method 5: Lambda and Sorted. Strengths: Quick and easy one-liner. Weaknesses: Cannot distinguish between different character types.