Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python one-liner to convert float to string

Tags:

python

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!

like image 717
Joe Flip Avatar asked Feb 22 '26 10:02

Joe Flip


1 Answers

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.]

like image 187
DSM Avatar answered Feb 24 '26 00:02

DSM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!