- 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
How to format numbers to strings in Python?
You can format a floating number to a fixed width in Python using the format function on the string.
example
nums = [0.555555555555, 1, 12.0542184, 5589.6654753] for x in nums: print("{:10.4f}".format(x))
Output
This will give the output −
0.5556 1.0000 12.0542 5589.6655
Example
Using the same function, you can also format integers −
nums = [5, 20, 500] for x in nums: print("{:d}".format(x))
Output
This will give the output −
5 20 500
Example
You can use it to provide padding as well, by specifying the number before d:
nums = [5, 20, 500] for x in nums: print("{:4d}".format(x))
Output
This will give the output −
5 20 500
The https://pyformat.info/ website is a great resource to use for learning all nuances of formatting numbers in python.
Advertisements