Here's one way using a list comprehension, and checking if the modulo operator of a given string converted to float is 0.0
, to either convert it to float
or to integer
.
Also note that it is not possible to directly use the built-in int
function to construct an integer from a string with decimals, to overcome this I'm using f-strings, where g
will print a given number as a fixed-point number, with in this case 0
decimal places:
l = ['67.50', '70.00', '72.50', '75.00', '77.50', '80.00', '82.50']
[int(f'{float(i):g}') if float(i)%1 == 0. else float(i) for i in l]
# [67.5, 70, 72.5, 75, 77.5, 80, 82.5]
For python versions under 3.6
use .format
for string formatting:
[int('{0:g}'.format(float(i))) if float(i)%1 == 0. else float(i) for i in l]
# # [67.5, 70, 72.5, 75, 77.5, 80, 82.5]