-3

I want to get rid of the white space at the end of each line.

w = input("Words: ")
w = w.split()
k = 1
length = []
for ws in w:
  length.append(len(ws))
  y = sorted(length)
while k <= y[-1]:
  if k in length:
    for ws in w:
      if len(ws) != k:
        continue
      else:
        print(ws, end=" ")
    print("")
  k += 1

The out put is giving me lines of words in assessing lengths eg if I type in I do love QI; I do QI love

But it has white space at the end of each line. If I try to .rstrip() it I also delete the spaces between the words and get; I doQI love

user3864194
  • 83
  • 2
  • 6
  • 3
    string.rstrip() would work for you. – Tanveer Alam Dec 02 '14 at 12:02
  • duplicate of http://stackoverflow.com/questions/2372573/how-do-i-remove-whitespace-from-the-end-of-a-string-in-python – Tanveer Alam Dec 02 '14 at 12:04
  • ^ Nope. Based on the OP's below comment "I have tried this but I keep losing the space between the words that are listed on the line." I think this is a duplicate of http://stackoverflow.com/questions/3739909/how-to-strip-all-whitespace-from-string – Sriram Dec 02 '14 at 12:13

3 Answers3

2

Use " ".join(ws) instead and it will auto but them on the same line (you will need to create a list rather than a string)

0

you need to use rstrip
demo:

>>> 'hello '.rstrip()
'hello'

rstrip removes any whitespace from right

lstrip removes whitespace from left:

>>> '  hello '.lstrip()
'hello '

while strip removes from both end:

>>> '  hello '.strip()
'hello'

you need to use split to convert them to list

>>> "hello,how,are,you".split(',')    # if ',' is the delimiter
['hello', 'how', 'are', 'you']
>>> "hello how are you".split()       # if whitespace is delimiter
['hello', 'how', 'are', 'you']
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
0
re.sub(r"[ ]*$","",x)

You use use re.sub of re module.

vks
  • 67,027
  • 10
  • 91
  • 124
  • You _could_, but why use regex for a problem that a builtin str method can handle? – PM 2Ring Dec 02 '14 at 12:38
  • From doing some reading I think this will work but Im not sure where to put it in context of my code? – user3864194 Dec 03 '14 at 00:51
  • @user3864194 x is a line which you pass.just put it in a loop and pass lines.return value would be line without spaces at end – vks Dec 03 '14 at 02:24