Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to modified digit

Tags:

python

I have the following numbers, which I want to convert:

'2.44' --> '2.44'
'12.83' --> '2.83'
'121.834' --> '1.83'

In other words, I want 1 digit to the left of the decimal point and two digits to the right. What would be the best way to do this? My current method is using:

number = '41.33'
index = number.index('.')
result = number[index-1] + '.' + number[index+1:index+3]

Is there a better, cleaner way to do this?

like image 870
David542 Avatar asked Feb 18 '26 14:02

David542


1 Answers

result = number[index - 1: index + 3]

that is all

like image 175
Joran Beasley Avatar answered Feb 21 '26 02:02

Joran Beasley



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!