B Hok
B Hok

Reputation: 155

Python 3 - How to continuously remove letters from a sentence?

alphabet_dic = ['a','b','c','d','e','f','g','h','i','j','k','l','n','o','p','q','r','s','t','u','v','w','y','z','m']

doc = Document('test3.docx')
firstSen = doc.paragraphs[0].text
print (firstSen)

indexLetters = 0
while indexLetters < len(c_dic):
    d_dic = c_dic[indexLetters]
    indexLetters += 1
    secondSen = firstSen.replace(d_dic,"")    
    print (secondSen)

The test document holds the sentence "Hello There". I am attempting to make a loop in where it checks the dictionary for a long range of specific letters and slowly loops and remove the letters from "Hello There".

Idea:

Sentence = Hello There

helloDic = ['h','e','l','o']

Desire Result = Tr

Any suggestions or better way to do this?

Upvotes: 3

Views: 309

Answers (2)

Elmex80s
Elmex80s

Reputation: 3504

The straightforward solution

sentence = 'Hello There'

hello_dic = ['h','e','l','o']

r = [s for s in sentence if s.lower() not in hello_dic]

print ''.join(r)

Output

' Tr'

Upvotes: 0

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140188

Applying str.replace several times comes to mind at first, but it is really a non-performant method to do that (Python str.translate VS str.replace)

As a nice alternative, you could modify your "dictionary" to create a real dictionary, compatible with str.translate (adding the uppercase letters too). Then you only have to apply the str.translate function to your string using the new dict:

Sentence = "Hello There"

helloDic = ['h','e','l','o']

rep_dic = {ord(k):None for k in helloDic + [x.upper() for x in helloDic]}

print(Sentence.translate(rep_dic))

result:

 Tr

(spaces were preserved)

Upvotes: 2

Related Questions