Menu
CoddyTech

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_label

Python

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 icon

Challenge

Beginner

Read 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__")
quiz iconTest yourself

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

All lessons in Python for Ruby Developers

Practice on your own: Online Python compiler