Names and Mutable Strings
Lesson 3 of 48 in Coddy's Python for Ruby Developers course.
Both languages bind local names to objects without declaring their types. A Python name can later refer to an object of another type, as a Ruby local can. Assignment does not duplicate the object in either language. Ruby strings are commonly mutable: replace changes a string through all aliases. Python strings are immutable. Assigning a replacement string changes one name, leaving an alias bound to the original string. Python lists remain mutable, so do not generalize the string difference to all objects. Uppercase Python names indicate constants by convention; they do not receive Ruby constant lookup behavior or runtime reassignment warnings.
Ruby
label = 'red'
alias_label = label
label.replace('blue')
puts alias_labelPython
label = 'red'
alias_label = label
label = 'blue'
print(alias_label)Porting trap
Distinguish rebinding from mutation before porting code that uses Ruby bang methods or string replacement. Python has no universal bang-method naming rule.
Challenge
BeginnerRead two lines: an initial status and a replacement status. Keep the initial value in original, reassign status to the replacement, then print the original value and current value on separate lines. Both lines can be empty. The input scaffold reads the replacement into replacement.
Print only the requested output, with a newline after each line. The supplied input lines read the test data; keep them and add your work below.
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 Ruby Developers
1From Ruby to Python
Run Your First Python ProgramStrings and InterpolationNames and Mutable StringsDivision and ParsingFrom end to IndentationRecap: Rewrite a Receipt4Iteration and Transformations
each and Python foreach_pair and enumeratenext Becomes continueselect, map, and sort_byRecap: Build a Ranking2Values and Decisions
nil Becomes None== and equal?Zero Is False in Pythonelsif and Conditional ValuesRecap: Eligibility Rules3Collections and References
Array Methods and ListsParallel Assignment and TuplesHash Defaults and Dict Keysdup, Copies, and SetsRecap: Clean an Inventory6Reliable Python Programs
gets, input, and Formattingrescue and Context Managersrequire and Import GuardsHints Do Not Enforce TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler