3
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?

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
B Hok
  • 145
  • 1
  • 6
  • 15

2 Answers2

2

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)

Community
  • 1
  • 1
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

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'
Elmex80s
  • 3,428
  • 1
  • 15
  • 23