1

I am using xlrd to read values from cells in an excel spreadsheet. Whenever I detect a cell type = 2, then I know it is a number. A number of 3 in cell will be returned as 3.0 And a number of 3.14 will be returned as 3.14

I will be converting numbers to text. What function should I use to remove zeroes right of the decimal and the decimal?

The above 2 numbers should be 3 and 3.14

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
panofish
  • 7,578
  • 13
  • 55
  • 96

2 Answers2

4

Use str.rstrip(), twice:

str_of_float.rstrip('0').rstrip('.')

This will remove trailing zeros, and if that leaves you with a trailing . it's removed as well.

Demo:

>>> '3.14'.rstrip('0').rstrip('.')
'3.14'
>>> '3.0'.rstrip('0').rstrip('.')
'3'
>>> '3000.0'.rstrip('0').rstrip('.')
'3000'

Don't be tempted to use .rstrip('.0'); it'll remove too many zeros:

>>> '3000.0'.rstrip('.0')
'3'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

I always use format when printing values to strings. Using the format specs, it gives a good deal of control over what is printed.

CDspace
  • 2,639
  • 18
  • 30
  • 36