Input and String Formatting
Lesson 27 of 48 in Coddy's Python for Swift Developers course.
Swift readLine returns an optional string; Python input returns a string or raises EOFError. Convert integer text with int before arithmetic. strip removes outer whitespace and split without arguments splits whitespace runs. Python f-strings embed expressions and accept format specifications such as zero padding. The tasks keep money as integer cents to avoid unnecessary floating rounding. Reusable helpers return results and the locked driver owns input/output.
Swift example
import Foundation
let label = " Green tea ".trimmingCharacters(in: .whitespaces)
let cents = 305
print(String(format: "%@: %d.%02d", 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 prompts, optional wrappers, or debug labels when the task expects exact output.
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 Swift Developers
1From Swift to Python
Run Your First Python ProgramPrinting and Stringslet, var, and RebindingInt Range and DivisionIndentation and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for and Half-Open Rangesenumerated to enumeratewhile and Loop Controlmap, filter, ComprehensionsRecap: Build a Ranking2Values and Decisions
Optionals and NoneEquatable and IdentityBool Conditions and FallbacksBranches and TernariesRecap: Eligibility Rules3Value Types to Shared Objects
Array to listTuples and UnpackingDictionary Lookup and OrderValue Copies and AliasesRecap: Clean an Inventory6Errors and Modules
Input and String Formattingthrows, defer, and withModules and Main GuardsHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler