Home > Net >  how to remove special word from a string in function
how to remove special word from a string in function

Time:11-03

Write a function fun(long string) with one string parameter that returns a string. The function should extract the words separated by a single space " ", exclude/drop empty words as well as words that are equal to "end" and "exit", convert the remaining words to upper case, join them with the joining token string ";" and return this newly joined string. my code is......

def fun(long_string): long_string = long_string.split(' ')

try:
    if 'exit' in long_string:
        long_string.remove('exit')
    elif 'end' in long_string:
        long_string.remove('end')
except ValueError:
                pass

..................... but it does not remove the "End or exit" .can someone pls help me to get it out. Im beginner in python and I stack here

CodePudding user response:

You could try this and convert into the function as you wish - it's very straightforward.

Code did not fully test yet (but works for your inputs), so please try different inputs and you can learn to "improve" it to meet your requirement. Please ask if you have any questions.

inputs =  "this is a long test exit string"     

stop_words = ('end', 'exit')

outs = ''

for word in inputs.split():
    if word in stop_words:
        outs = inputs.replace(word, " ")

ans = ';'.join(w.upper() for w in outs.split())  # do the final conversion

Confirm it:

assert ans == "THIS;IS;A;LONG;TEST;STRING"    # silent means True

Edit: add function:

def fun(long_string):
    #s = "this is a long test exit string" 

    stop_words = ('end', 'exit')
    outs  = ''

    for word in long_string.split():
        if word in stop_words:
            outs = long_string.replace(word, " ")
    
    ans = ';'.join(w.upper() for w in outs.split())
    return ans
        
text = "this is a long test exit string" 
print(fun(text))
  • Related