-1

I'm looking for a solution to removing the trailing white space when inputting a string of numbers.

Code

vals_inp=input()
print('vals_inp',vals_inp)

vals_strip = vals_inp.rstrip()
print('vals_strip', vals_strip, type(vals_inp))

in_set=set(vals_strip) # problem happens here

OUTPUT

in_set {'1', '2', '3', ' '} #PROBLEM ' '

Things tried

I have tried rstrip lstrip rstrip and strip(' ') I see lots of answers using rstrip etc but its not working for me

Why it matters

The ' ' in my set is messing up the subsequent code. All help appreciated

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
WickHerd
  • 67
  • 7
  • If your input is ``1 2 3`` then the ``' '`` is the *separator* of your numbers. A [mre] showing the actual input, or at least the output *corresponding to the script*, would help. – MisterMiyagi Oct 25 '21 at 10:27
  • Does this answer your question? [Get a list of numbers as input from the user](https://stackoverflow.com/questions/4663306/get-a-list-of-numbers-as-input-from-the-user) – MisterMiyagi Oct 25 '21 at 10:28

2 Answers2

0

Check this:

vals_inp=input()
print('vals_inp',vals_inp)

vals_strip = vals_inp.rstrip()
print('vals_strip', vals_strip, type(vals))

in_set=set(vals_strip) # problem happens here
RiveN
  • 2,595
  • 11
  • 13
  • 26
Awais Khan
  • 39
  • 4
  • vals_strip = vals.rstrip() ---> vals_strip = vals_inp.rstrip() – Awais Khan Oct 24 '21 at 10:45
  • Thank you for your help. I see the correction. but it hasnt solved it. Now I have: vals_inp=input() vals_strip = vals_inp.rstrip() in_set=set(vals_strip) print('in_set', in_set, type(in_set)) but output is still: in_set {'1', '2', '3', ' '} - ie ' ' is still there – WickHerd Oct 24 '21 at 10:51
  • 1
    vals = [x for x in vals_inp if x != ''] – Awais Khan Oct 24 '21 at 10:54
  • Thank you !!! - rearranging the order I got it to work: vals_inp=input() list_set = list(vals_inp) vals = [x for x in list_set if x != ' '] set_vals = set(vals) OUTPUT: {'1', '3', '2'} – WickHerd Oct 24 '21 at 11:09
  • This answer seems to provide the same code as the question. How does it fix the problem? – MisterMiyagi Oct 25 '21 at 10:32
0

Thanks to @Awais Khan answer:

vals_inp=input() 
list_set = list(vals_inp) 
vals = [x for x in list_set if x != ' '] 
set_vals = set(vals) 
OUTPUT: {'1', '3', '2'}\
RiveN
  • 2,595
  • 11
  • 13
  • 26
WickHerd
  • 67
  • 7
  • 1
    Note that this is needlessly creating two lists, one of which is rather inefficient; you could just use ``set_vals = set(vals_inp.replace(' ', '')`` directly. – MisterMiyagi Oct 25 '21 at 10:34
  • Thanks for the shorter solution, for me, I still need the steps so it's clear what is happening – WickHerd Oct 27 '21 at 07:57