Python Forum

Full Version: Remove special character from list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi guys, if I would to put ' symbol in the symbols, it is obvious that I won't be getting the desire outcome.

I would like to preserve the ' symbol on don't isn't and wouldn't. I've tried with endswith method but still got it wrong. Hope you could help on this.

Current outcome
["Examples", "of", "contractions", "include", "dont", "isnt", "and", "wouldnt"]

Desire outcome
["Examples", "of", "contractions", "include", "don’t", "isn’t", "and", "wouldn’t"]


sentence = "Examples of contractions include: don't, isn't, and wouldn't"

list_sentence = sentence.split()
print(list_sentence)

symbols = "{}()[].,:;-*/&|<>=~$123456789?"

results = []

for element in list_sentence:
    temp = ""
    
    for ch in element:
        if ch not in symbols:
            temp += ch
                
    results.append(temp)

print(results)
I tried the code and it gives the desired output.
Hi Gribouilis, thank you for replying.

Yeah, because I've removed ' symbol from symbols. I guess my codes won't work for this circumstances.
Before the loop through ch in element, replace any instance of "n't" with something improbable like 'nzxzt'. Then after that loop, but before you append to results, replace 'nzxzt' with "n't". This can easily be done with the replace method of strings.