2025, Dec 15 21:00
Print a Float with One Decimal and a Trailing C in Python Without a Space (f-Strings Guide)
Use Python string formatting and f-strings to print a float to one decimal with a trailing C and no space. Learn .1f, fill characters, width to avoid padding.
When you format numeric output in Python, a tiny whitespace can derail the expected string. A common case is printing a float with one decimal place followed by a unit like C, and ending up with an unintended gap between the number and the unit.
Problem
The task: read a float, keep exactly one digit after the decimal point, and append the letter C immediately after the number.
temp_value = float(input())
print('{:C>.1f}'.format(temp_value), 'C')
Observed output looks like 36.4 C, while the expected output is 36.4C.
What’s going on
There are two independent aspects at play. First, printing the number and the literal C as separate arguments produces a space between them in the final line. That’s why you see 36.4 C instead of 36.4C. Second, the C placed inside the format specifier in {:C>.1f} is not a literal suffix; it is a fill character. It only takes effect together with an explicit width. For example, setting a width pads the field with C on the left: '{:C>10.1f}'.format(123.456) results in CCCCC123.5. This padding is unrelated to adding a unit to the right of the number.
Fix and working examples
The simplest way to produce the exact string without the unwanted space is to build a single formatted string and place C directly in it.
reading = float(input())
print(f"{reading:.1f}C")
This prints a float rounded to one decimal place with C attached immediately. If you only need to attach the unit without changing precision, you can write:
reading = float(input())
print(f"{reading}C")
You can also control the number of decimal places explicitly, keeping trailing zeros when needed:
reading = float(input())
print(f"{reading:.2f}C") # two decimal places
reading = float(input())
print(f"{reading:.3f}C") # three decimal places
Why this matters
String formatting is exacting. Small differences—like a single space or a missing trailing zero—change outputs and break comparisons. Understanding how format specifiers work and how to construct a single, complete string helps you produce deterministic, testable results.
Takeaways
Combine the numeric value and its unit in one formatted string to avoid unintended spacing. Treat characters like C inside a format spec as a fill character, which only affects padding when a width is set. For precise control over the number of decimal places, use the .nf precision in an f-string so the output matches what you intend, character for character.