4

In main.py i have this

import RemoveShortWords as rs

procLine="the   in  shear flow past a flat plate"
procLine = rs.RemomeOneTwoCharWords(procLine)
print(procLine)

and RemoveShortWords.py is this

def RemomeOneTwoCharWords(procLine):

    procLine = str(procLine)

    for word in procLine.split():

        if(len(word)<=2):
            procLine = procLine.replace(word,"")


    return procLine

print returns this

the sher flow pst flt plte

as you can see function removes words with less than 2 characters. But, for some reason, it removed all "a" characters too. For Example, "flat" became "flt"

Why?

Eric Klaus
  • 923
  • 1
  • 9
  • 24
  • @PM2Ring, sometimes people may miss things. Why not just try to help to explain what's wrong, instead of posting useless comment? – Eric Klaus Sep 23 '18 at 01:02
  • @PM2Ring , it is not duplicate, i'm not asking how to remove 2 char words, I asked why code performed not as intended – Eric Klaus Sep 23 '18 at 01:04
  • 2
    Reopening. The question is about why the code fails; the dupe target did not contain an answer to that question. It may be related, but it's not a dupe. – user2357112 Sep 23 '18 at 01:08

3 Answers3

6

The variable procLine has the in shear flow past a flat plate

And procLine.split() ['the', 'in', 'shear', 'flow', 'past', 'a', 'flat', 'plate']

In for loop, it finds a and replaces a in procLine with empty or removes the character. Note: it would do same if some word was with in e.g. string to strg.

Instead I would suggest something like list comprehension may work:

procLine = ' '.join([w for w in procLine.split() if len(w)>2])
niraj
  • 17,498
  • 4
  • 33
  • 48
3

replace replaces all occurrences.

str.replace(old, new[, count])

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

Documentation

So once the word "a" is reached in the input, procLine.replace("a", "") will remove all "a"s in the entire string. If you only want to replace words shorter than 2 characters, you could use for example list-comprehension:

return ' '.join([s for s in procLine.split(' ') if len(s) > 2])
Community
  • 1
  • 1
  • @PM2Ring Interesting; I didn't know that one. Thanks for the info :) I'll edit –  Sep 23 '18 at 15:10
0

One thing i think is confusing you is procLine.split() doesn't actually modify procLine.

def RemomeOneTwoCharWords(procLine):
    procLine = str(procLine)
    temp = ""
    for word in procLine.split():
        if len(word)>=2:
            temp += word + " "
    return(temp)
 
procLine="the   in  shear flow past a flat plate"
procLine = RemomeOneTwoCharWords(procLine)
print(procLine)

gives

the shear flow past flat plate
Subham
  • 397
  • 1
  • 6
  • 14