Assume we have a list:
list_t = ['1.234', '3.6654', '7.134123', '2.2323', 'Someone']
our operation should change the above list of string to float value with rounding the float value till 2 points except the last string.
expected output will be:
list_t = [1.23, 3.67, 7.13, 2.23, 'Someone']
If the string is always present in the last index, you can use this simple list comprehension:
list_t = ['1.234', '3.6654', '7.134123', '2.2323', 'Someone']
list_t = [round(float(num),2) for num in list_t[:-1]] + [list_t[-1]]
print(list_t)
Output:
[1.23, 3.67, 7.13, 2.23, 'Someone']
If the string can be at any position, you don't have to use a try-except block or something. You can use this list comprehension:
list_t = ['1.234', '3.6654', '7.134123', '2.2323', 'Someone']
list_t = [round(float(num),2) if num.replace('.', '', 1).isdigit() else num for num in list_t]
print(list_t)
Output:
[1.23, 3.67, 7.13, 2.23, 'Someone']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With