Click here to Skip to main content
15,888,527 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Returns a string that has all the characters that are in word, in the same order, except for the ones that are in char_list.


What I have tried:

def remove_chars(word, char_list):
    # returns str with characters in same order as in word
    # except the ones in char_list
    
    for char in word:
        if char in char_list:
            char = 'extra'
            word= word.replace(char, '')
            
        else:
            char = char
           
    return word
Posted
Updated 6-Oct-20 10:14am
Comments
Patrice T 6-Oct-20 11:15am    
Show sample input with actual output and expected output

What is this supposed to be for: char = 'extra'?
All you need is
Python
def remove_chars(word, char_list):
    # returns str with characters in same order as in word
    # except the ones in char_list
    
    for char in word:
        if char in char_list:
            word= word.replace(char, '')
           
    return word
 
Share this answer
 
Quote:
as I am writing its function it is not working. I can't figure out why.

I would start by simplifying the code to:
Python
def remove_chars(word, char_list):
    # returns str with characters in same order as in word
    # except the ones in char_list
    
    for char in word:
        if char in char_list:
            char = 'extra'
            word= word.replace(char, '')
            
        else:
            char = char
           
    return word

Then I would reverse the loop to:
Python
def remove_chars(word, char_list):
    # returns str with characters in same order as in word
    # except the ones in char_list
    
    for char in char_list:
        word= word.replace(char, '')
    return word

because not all languages can handle looping in a list while messing with it at same time.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900