Menu
CoddyTech

Text Input and Exact Output

Lesson 27 of 48 in Coddy's Python for Java Developers course.

Keep parsing separate from formatting. Python input() returns a line of text without its terminating newline, resembling line-based Java input rather than Scanner.nextInt. Convert with int when numeric meaning is required. strip removes surrounding whitespace, not interior spaces. An f-string inserts expressions; :02d pads an integer with zeroes to at least two digits. Integer cents avoid introducing binary floating-point rounding into this output. The examples emit Green tea: 3.05 followed by a newline.

Java excerpt: inside main

String label = "  Green tea  ".strip();
int cents = 305;
System.out.printf(java.util.Locale.ROOT, "%s: %d.%02d%n", label, cents / 100, cents % 100);

Python

label = "  Green tea  ".strip()
cents = 305
print(f"{label}: {cents // 100}.{cents % 100:02d}")

Watch the difference

Python str.split(",") uses a literal separator and preserves empty fields, including trailing ones. Java String.split uses a regular expression and its default overload drops trailing empty fields. Do not copy parser assumptions across languages.

Practice

Apply this comparison in the task below. Editable files: main.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

challenge icon

Challenge

Beginner

Read a label and a nonnegative cents amount from two lines. Trim only the label's surrounding whitespace, keeping internal spaces. Output label: dollars.cents with exactly two fractional digits. An empty label yields a line beginning : . Omit prompts and currency symbols. Python f-string width formatting replaces the Java printf pattern for the integer cents remainder.

Editable files: main.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

Keep the supplied input scaffold. Output only the requested results, with a newline after each line and no prompts.

Try it yourself

# Starts the program in main.py. Edit main.py to solve the challenge.
from runpy import run_module

run_module("main", run_name="__main__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Java Developers

Practice on your own: Online Python compiler