+ 1
Python spitted string decimals precision
Hi I have a string which has three parts separated by two spaces. I need to provide decimal to each part . How to do it effectively? For example, '1.34 2.36 4.567' should have output 1.3 2.4 and 4.6 if precision is 1 decimal Please suggest. My half cooked sample code as below: https://sololearn.com/compiler-playground/cAvrLn5wNz0F/?ref=app
6 Respuestas
+ 4
Ketan Lalcheta ,
here is an other suggestion that is short and concise:
a = '1.23456789 2.3567 1.2334' # a -> string
for item in a.split(): # item -> string
print(f'{float(item):.1f}',end=' ') # convert string to float, format float and output as string
# result -> 1.2 2.4 1.2 (data type is string)
+ 3
Ketan Lalcheta ,
what you get with your code is a list of strings (numbers).
to get the items as float, we can use map() function like this:
...
lst = list(map(float, a.split()))
...
the output can be done with an f- string with a defined precision like:
...
print(f'{lst[0]:.1f}') # 1 -> precission, f -> float data type
+ 3
Ketan Lalcheta ,
f-string is generating a string output. we can use a loop to print the 3 `numbers` and set the `end` parameter to a space as separator between the items:
...
for item in lst:
print(f'{item:.1f}',end=' ')
+ 3
a = '1.23456789 2.3567 1.2334'
b = ' '.join((str(round(float(n),1)) for n in a.split(' ')))
print(type(b))
print(b)
+ 1
thanks.
I probably drafted a question wrongly.
I let me try again. I don't want to have three different parts individually at the end.
It should still be a string at the end also but with precision in each part and also joined with space
Meaning
'1.34 2.36 4.567' would be '1.3 2.4 4.6' as output if precision was asked as 1
your suggestion work also , but is there any other approach if end result required is in string format.