Reputation: 1195
I want to convert a float between 0.0 and 39.9 into a string. Replace the tens digit with an L, T or Y if it's a 1, 2 or 3 respectively. And append an M if it's in the ones. For example, 22.3 would return T2.3 and 8.1 would return M8.1 and so forth. Otherwise, return the float.
This code works of course, but I wondering if there was a simpler (if not one-liner) solution. Here's the code:
def specType(SpT):
if 0 <= SpT <= 9.9:
return 'M{}'.format(SpT)
elif 10.0 <= SpT <= 19.9:
return 'L{}'.format(SpT - 10)
elif 20.0 <= SpT <= 29.9:
return 'T{}'.format(SpT - 20)
elif 30.0 <= SpT <= 39.9:
return 'Y{}'.format(SpT - 30)
else:
return SpT
Thanks!
Upvotes: 3
Views: 263
Reputation: 353039
How about:
def specType(SpT):
return '{}{}'.format('MLTY'[int(SpT//10)], SpT % 10) if 0.0 <= SpT <= 39.9 else SpT
which gives
>>> specType(0.0)
'M0.0'
>>> specType(8.1)
'M8.1'
>>> specType(14.5)
'L4.5'
>>> specType(22.3)
'T2.3'
>>> specType(34.7)
'Y4.7'
[As noted in the comments, you'll want to think about what to do with numbers which can sneak through your boundaries -- I made one guess; modify as appropriate.]
Upvotes: 10