Modifying Text¶
We can loop through the string and modify it using find
and slice
(substring).
Note
It might be a good idea to review Strings are Objects before going ahead with this section.
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.
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?
Can you loop through and encode a string to hide the contents of the message?
-
csp-9-4-1: What character is e replaced with when the message is encoded?
- a
- The letter in a_str is replaced with the letter at the same position in e_str.
- d
- The letter in a_str is replaced with the letter at the same position in e_str.
- w
- Try counting the letters in a_str to figure out how many letters to count in e_str.
- v
- The letter e is at position 4 in a_str and will be replaced with the letter v at position 4 in e_str.
-
csp-9-4-2: What is the value of encoded_message 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 a_str is replaced with the letter at the same position in e_str.
- "n"
- The letter in e_str at the same position as the m in a_str is n.
- "m"
- Notice that we are adding the letter in e_str at pos not the letter in a_str at pos.
csp-9-4-4: 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 = ""
a_str = "abcdefghijklmnopqrstuvwxyz. "
e_str = "zyxwvutsrqponmlkjihgfedcba ."
encoded_message = "nvvg.nv.zg.nrwmrtsg"
---
for letter in encoded_message:
---
pos = e_str.find(letter)
---
message = message + a_str[pos]
---
print(message)
Write the code to replace every 0 with o in the given string ‘The 0wl h00ts l0udly’.