Modifying Text

We can loop through the string and modify it using find and slice (substring).

Google has been digitizing books. But, sometimes the digitizer makes a mistake and uses 1 for i. The following program replaces 1 with i everywhere in the string. Now you might not want to really replace every 1 with i, but don’t worry about that right now. It uses a while loop since we don’t know how many times it will need to loop.

(Change_Ones)

You don’t have to replace just one character. You could replace every instance of a word with another word. For example, what if you spelled a word wrong and wanted to change it everywhere?

(Change_Word)

Can you loop through and encode a string to hide the contents of the message?

(Encode_String)

    csp-9-4-1: What character is e replaced with when the message is encoded?
  • a
  • The letter in str is replaced with the letter at the same position in eStr.
  • d
  • The letter in str is replaced with the letter at the same position in eStr.
  • w
  • Try counting the letters in str to figure out how many letters to count in eStr.
  • v
  • The letter e is at position 4 in str and will be replaced with the letter v at position 4 in eStr.
    csp-9-4-2: What is the value of encodedMessage after the loop executes the first time?
  • ""
  • It starts out as the empty string, but a letter is added each time through the loop.
  • "o"
  • The letter in str is replaced with the letter at the same position in eStr.
  • "n"
  • The letter in eStr at the same position as the m in str is n.
  • "m"
  • Notice that we are adding the letter in eStr at pos not the letter in str at pos.
        csp-9-4-3: The program below decodes an encoded message, but the lines are mixed up.  Put the lines in the right order with the right indentation.message = ""
str = "abcdefghijklmnopqrstuvwxyz. "
eStr = "zyxwvutsrqponmlkjihgfedcba ."
encodedMessage = "nvvg.nv.zg.nrwmrtsg"
---
for letter in encodedMessage:
---
    pos = eStr.find(letter)
---
    message = message + str[pos:pos+1]
---
print(message)
        

Write the code to replace every 0 with o in the given string ‘The 0wl h00ts l0udly’.

Show Comments

Note

Discuss topics in this section with classmates.

Show Comments
Next Section - Chapter 9 - Summary