bonezizzle
bonezizzle

Reputation: 1

Why are the variables in my string not concatenating with the join function?

I am trying to make a function that sorts all the digits in an integer in reverse. I am trying to get [5431] but instead the output is [5, 4, 3, 1]. I cannot figure out what I am doing incorrectly with the join function.

  def Descending_Order(num):
      num = [int(i) for i in str(num)]
      num.sort(reverse=True)
      num = str(num)
      "".join(num)
      print num
  Descending_Order(1534)

Upvotes: 0

Views: 41

Answers (2)

user8426627
user8426627

Reputation: 943

Look at that :

 num = str(num)

num is array, so str(num) is a string '[5, 4, 3, 1]', then you "".join(one string) bug give out num. The right is :

def Descending_Order(num):
  num = [int(i) for i in str(num)]
  num.sort(reverse=True)

  print ("".join(str(x) for x in  num))
Descending_Order(1534)

Upvotes: 1

Aero Blue
Aero Blue

Reputation: 526

Here is a simplified version that you might like:

def Descending_Order(num):

    return "".join(sorted(str(num), reverse=True))

print(Descending_Order(1534))

Expected Result:

5431

Upvotes: 0

Related Questions