Home > Back-end >  How to round a list of strings and keep them as a string?
How to round a list of strings and keep them as a string?

Time:09-23

I am trying to write a for loop to round the numbers in "numbers" to a single decimal place and I want to contain a single string. The following code was provided:

numbers = "1.111, 3.333, 5.555, 7.777, 9.999"
numbers = numbers.split( ", " )

the output should be:

numbers = ", ".join( numbers )
print( "Q5: 1.1, 3.3, 5.6, 7.8, 10.0? ->", numbers )

CodePudding user response:

or maybe some list comprehension?

numbers = "1.111, 3.333, 5.555, 7.777, 9.999"
numbers = numbers.split( ", " )

numbers = [str(round(float(x), 1)) for x in numbers]
numbers = ', '.join(numbers)

print(numbers) # 1.1, 3.3, 5.6, 7.8, 10.0
print(type(numbers)) # <class 'str'>

CodePudding user response:

You can do it using string formatting alone. The rounding is done using the format specifier '.1f' to display it using fixed point notation with 1 digit past the decimal point

numbers = "1.111, 3.333, 5.555, 7.777, 9.999"
numbers = numbers.split(", ")

i = 0
for number in numbers:
    # Cast each string number to a float, and use f-string format 
    # specifier to display properly
    number_converted = f"{float(number):.1f}"
    # Add the new string back to the original list
    numbers[i] = number_converted
    i  = 1

numbers_output = ", ".join(numbers)
print(numbers_output)
  • Related