Program to find number with thousand separator in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number n, we have to return this number into string format where thousands are separated by comma (",").

So, if the input is like n = 512462687, then the output will be "512,462,687"

To solve this, we will follow these steps −

  • res := n as string

  • res := reversed form of res

  • ans := a blank string

  • for i in range 0 to size of res - 1, do

    • if i mod 3 is same as 0 and i is not same as 0, then

      • ans := ans concatenate ','

    • ans := ans concatenate res[i]

  • ans := reversed form of ans

  • return ans

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

def solve(n):
   res = str(n)
   res = res[::-1]

   ans = ""
   for i in range(len(res)):
      if i%3 == 0 and i != 0 :
         ans += ','
      ans += res[i]

   ans = ans[::-1]

   return ans

n = 512462687
print(solve(n))

Input

512462687

Output

512,462,687
raja
Published on 17-May-2021 12:45:05
Advertisements