- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find number with thousand separator in Python
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 −
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
Advertisements