-2

This function takes one string parameter. Assume the string will be a series of integers separated by spaces. Ignore any extra whitespace. The empty string or a whitespace string return the empty string. Otherwise, the function returns a string with the argument’s integers separated by spaces but now in sorted order. Do not check for invalid strings. For instance, if the argument is 43 -1 17, the function returns -1 17 43.`

it does not work in a situation where the input is \t42 4 -17 \n

def sort_int_string(string):
        strlist = string.split(' ')
        new = []
        for value in strlist:
            value2 = int(value)
            new.append(value2)
        new = sorted(new)
        strlist2 = []
        for number in new:
            number = str(number)
            strlist2.append(number)
        final = ' '.join(strlist2)
        return final
jpp
  • 159,742
  • 34
  • 281
  • 339
  • 1
    Can you please let us know anything that you've tried to solve this so far, this may let us know where we can help you with anything you are stuck on – Dexygen Aug 30 '18 at 22:05
  • This is the code I have so far... def sort_int_string(string): strlist = string.split(' ') new = [] for value in strlist: value2 = int(value) new.append(value2) new = sorted(new) strlist2 = [] for number in new: number = str(number) strlist2.append(number) final = ' '.join(strlist2) return final – Jorge Gomez Del Campo Aug 30 '18 at 22:06
  • @JorgeGomezDelCampo Please move that code out of the comment and into your question – Dexygen Aug 30 '18 at 22:07
  • What seems to be the problem? Your code returns '-1 17 43'. What did you expect? – VanTan Aug 30 '18 at 22:26
  • it does not work in a situation where the input is "\t42 4 -17 \n" – Jorge Gomez Del Campo Aug 30 '18 at 22:29

3 Answers3

2

based on your comment, change the line:

strlist = string.split(' ')

to

strlist = string.split()

That should work because when sep is not specified, it defaults to white space. [ \t\n\r\f\v] are all white spaces.

VanTan
  • 617
  • 4
  • 12
1

@VanTan has explained the problem with your code. But you can also use:

x = '43 -1 17'

res = ' '.join(map(str, sorted(map(int, x.split()))))

# '-1 17 43'
jpp
  • 159,742
  • 34
  • 281
  • 339
0

This list comprehension should handle the whitespace you are encountering:

s = "\t42 4 -17 \n"
sorted([int(x) for x in " ".join(s.split()).split()])

[-17, 4, 42]

Lee
  • 405
  • 2
  • 10