Text Input and Formatting
Lesson 27 of 48 in Coddy's Python for Rust Developers course.
Rust read_line fills a mutable buffer and returns a Result. Python input() returns a string with its trailing newline removed, and raises EOFError if input is exhausted. Parse with int before doing integer arithmetic. strip() removes surrounding whitespace; split() without a separator divides on whitespace runs. Python f-strings evaluate expressions inside braces. Keep currency in integer cents for these exercises and format the remainder with two digits. The supplied drivers own input and output, so helpers should return values.
Rust excerpt inside main
let label = " Green tea ".trim();
let cents = 305;
println!("{}: {}.{:02}", label, cents / 100, cents % 100);Python
label = " Green tea ".strip()
cents = 305
print(f"{label}: {cents // 100}.{cents % 100:02d}")Porting trap
Do not print Rust-style debug representations or input prompts in a function graded by exact output. Also avoid stripping a field when its surrounding whitespace is meaningful.
Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.
Challenge
BeginnerRead a product label on the first line and a nonnegative integer number of cents on the second. Remove surrounding whitespace from the label but preserve internal spaces. Print exactly label: dollars.cents, with two digits after the decimal point and a final newline. The label may be empty, in which case the output begins with : . Do not print a currency symbol or input prompts.
Your code goes in main.py. The locked driver.py starts your program and cannot be edited.
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__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler