pythonstringstring-formatting

Why am I getting an extra space here?


air_temperature = float(input())
print('{:C>.1f}'.format(air_temperature), 'C')
Your output:    36.4 C
Expected output 35.4C

Error Message

Why am I being told there is an extra space here that is extraneous, and how do I get rid of it?

I am learning about string formatting, and thought I followed the instructions correctly.

I am trying to have only 1 place after the decimal in my float, followed by a C. I have to have the '{}' part in it, and it looks to me to be correct, but is showing that I have an extra space for some reason after the float, before the "C".

What can I try next?


Solution

  • You can use f-string instead:

    air_temperature = float(input())
    print(f"{air_temperature}C")
    
    input:  36.4
    output: 36.4C
    

    [Update]: You can still make it to multiple decimal points:

    up to 1 decimal point:

    air_temperature = float(input())
    print(f"{air_temperature:.1f}C")
    

    output:

    input: 36.4158102
    output: 36.4C

    up to 2 decimal points:

    air_temperature = float(input())
    print(f"{air_temperature:.2f}C")
    

    output:

    input:  36.4
    output: 36.40C
    

    up to 3 decimal points:

    air_temperature = float(input())
    print(f"{air_temperature:.3f}C")
    

    output:

    input:  36.4
    output: 36.400C