Python Forum
Remove special character from list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Remove special character from list (/thread-13868.html)



Remove special character from list - vestkok - Nov-04-2018

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)



RE: Remove special character from list - Gribouillis - Nov-04-2018

I tried the code and it gives the desired output.


RE: Remove special character from list - vestkok - Nov-04-2018

Hi Gribouilis, thank you for replying.

Yeah, because I've removed ' symbol from symbols. I guess my codes won't work for this circumstances.


RE: Remove special character from list - ichabod801 - Nov-04-2018

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.