Search code examples
pythonstringconditional-statementsprocedurepysimplegui

How To Remove Characters from String based on Some Conditions


Dears,

How To Remove Characters from String based on Some Conditions ? Knowing that I have one string where I need to :

  1. STEP 01 : Remeove vowels
  2. STEP 02 : Remove Duplicate consonants and keep the 1st appeared one.
  3. STEP 03 : Remove 1st and Last Characters if string starts/Ends with a given letter.

Example : Word : Transmuted

After Step01 ( Removing Vowels) => Trnsmtd After Step02 ( Removing Duplicate Consnants , here "2nd t", "2nd n", "2nd s" ) ==> Trnsmd After Step03 ( Removing 1st and Last Characters if word starts or ends with "t" and "d" => rnsm

Here is my first part of python Script , need the remaining 2 Steps:

string = "Transmuted"

vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
result = ""

for i in range(len(string)):
    if string[i] not in vowels:
    result = result + string[i]

    print("\nAfter removing Vowels: ", result)

OUTPUT : After removing Vowels: Trnsmtd


Solution

  • Here's another version of Step 01:

    word = 'THERMOCHEMISTRY'
    
    vowels={'a','e','i','o','u'}
    result = ''.join([letter for letter in word if letter.lower() not in vowels])
    

    For step 02, you could do this (there are probably more efficient methods, but this works):

    result2 = ""
    for i in result:
        if i.lower() not in result2 and i.upper() not in result2:
            result2 += i
           
    

    For step 03

    filter_out = {'d','t'}
    result3 = result2[1:] if result2[0].lower() in filter_out else result2
    result3 = result3[:-1] if result3[-1].lower() in filter_out else result3
    
    print(result + ' '+result2+' '+result3)
    # THRMCHMSTRY THRMCSY HRMCSY