Skip to main content

Featured

Space Explorers Book 7: Answers and Explanations

Memunic Space Explorers › Book 7: Memoon and the Search for Another Home › Answers and Explanations Answers and Explanations Habitable means life could live there; inhabited means life does live there. A world can be habitable and empty, as an unoccupied flat has a roof and water but nobody in it. The Moon has almost no air, so water would boil or freeze, and its gravity is only about one-sixth of Earth’s, too weak to keep air. Accept also: no greenhouse blanket, so it swings between very hot and very cold. Venus. It matches Earth in size and roughly in mass, but its thick carbon dioxide air traps heat, making it hot and crushing. “Twin” is only true for size and weight. A dip of 1 per cent means (planet width divided by star width) squared is 0.01, so the ratio is 0.1: the planet is about a tenth as wide as the star. Repeats at the same gap show the planet is going round the star in 12 days, and rule out a one-time event such as a passing object. A planet shines only by reflected l...

Byte by Byte Book 7: Chapter 4 – Working with Strings

Byte by Byte › Book 7: Networks, Programming and Machine Learning › Chapter 4: Working with Strings

Chapter 4: Working with Strings

You will learn: how Python stores text as strings, escape characters, indexing and negative indexing, slicing, why strings are immutable, the most useful string methods, the in operator, looping through strings, ord() and chr(), formatted output, and how to write a Caesar cipher program and a letter-frequency counter.

🔎 The Case

Beautine arrived at Snowpeak with her tail fluffed out to twice its usual size, which meant she was either furious or delighted. It turned out to be both.

"I am Keeper of Records," she announced, "and nobody asked me to keep these records. So I kept them anyway." She had copied every post about the fake picture from every message board in Memunic: 12,384 of them. "They are a mess," she added. "Capitals everywhere. Extra spaces. Spelling that would make Kachui weep."

Memoon read a few on screen.

" The Guardian SHOWS his true face! #Simbah "

"cant believe it... poor rabbits #simbah"

"This is OBVIOUSLY edited, Simbha would never!!!"

"Last year," said Memoon, "I only used Python for numbers and turtles. I never used it for words."

"Words are just data," said Nimo. "Every letter is a number underneath, remember? Python can handle text as easily as numbers, if you know how to hold it."

Memoon opened IDLE and typed the first post into a variable. If she could understand one post completely, she could understand twelve thousand.

💡 The Concepts

Strings. In Python, text is stored as a string: a sequence of characters inside quotation marks. You met strings in Book 6 as the str data type. Single and double quotes both work; triple quotes let a string run over several lines.

name = "Memoon"
village = 'Moonbrook'
notice = """Truth Desk
Open every day
Ask before you share"""

A string can hold letters, digits, spaces, punctuation, emoji and characters from any language, because Python 3 uses Unicode (Book 6).

Basic operations.

OperationExampleResult
Lengthlen("Snowpeak")8
Join (concatenate)"Snow" + "peak""Snowpeak"
Repeat"ha" * 3"hahaha"

Compare "cat" == "Cat" False (case matters)

Convert a numberstr(42)"42"

Escape characters. Some characters cannot be typed directly inside a string, so Python uses a backslash followed by a letter, called an escape character (or escape sequence).

EscapeMeaning
\nNew line
\tTab
\'A single quote inside a single-quoted string
\"A double quote inside a double-quoted string
\\A real backslash
print("Line one\nLine two\tTabbed")
print('It\'s Memoon')

Output:

Line one
Line two    Tabbed
It's Memoon

Indexing. Each character in a string has a position number called an index. Python counts from 0, not 1. You can also count backwards from the end using negative indexes: −1 is the last character.

CharacterSNOWPEAK
Index01234567
Negative index−8−7−6−5−4−3−2−1
word = "SNOWPEAK"
print(word[0], word[3], word[-1], word[-2])

Output: S W K A . Asking for an index that does not exist, such as word[8] , gives an IndexError .

Slicing. A slice takes a piece of a string: text[start:stop:step] . It starts at start and stops just before stop . Leave out start to begin at the beginning; leave out stop to go to the end; step says how many to jump.

SliceMeaningResult
word[0:4]Indexes 0, 1, 2, 3"SNOW"
word[4:]From 4 to the end"PEAK"
word[:3]From the start up to (not including) 3"SNO"
word[::2]Every second character"SOPA"
word[::-1]The whole string backwards"KAEPWONS"

The rule "stop just before" works like range() in Book 6, and it means word[:4] + word[4:] always gives back the whole word.

Strings are immutable. Immutable means "cannot be changed". You cannot change one character of a string in place:

animal = "lion"
animal[0] = "L"

This gives TypeError: 'str' object does not support item assignment . Instead, you build a new string and store it in the variable: animal = "L" + animal[1:] . Every string method below returns a new string; the original stays the same.

String methods. A method is a function that belongs to a particular type of data. You call it with a dot after the value: text.upper() .

MethodWhat it doesExampleResult

.upper() / .lower( All capitals / all small letters "Hop".upper() "HOP"

)
.title()Capital at the start of each word"pebble hollow".title()"Pebble Hollow"
.capitalize()Capital at the start only"hello there".capitalize( )"Hello there"
.strip()Removes spaces (and new lines) from both ends" hi ".strip()"hi"

.replace(old, new) Replaces every old with ne "a-b- "a+b+c"

wc".replace("-", "+")

.find(sub) Index where sub first "Moonbrook".find(" 4

appears, or −1 if not foundbrook")
.count(sub)How many times sub appears"banana".count("a" )3

.startswith(s) / .e True if it starts / ends with s "photo.png".endswi True

ndswith(s)th(".png")
.isdigit()True if every character is a digit"2026".isdigit()True
.isalpha()True if every character is a letter"Nimo".isalpha()True
.isalnum()True if every character is a letter or digit"B7".isalnum()True

.isupper() / .islow True if all letters are capitals / "OK".isupper() True

er()small
.split()Breaks a string into a list of words"a b c".split()['a', 'b', 'c']

You will use .split() and the lists it makes in Chapter 5.

The in operator. in checks whether one string appears inside another, giving True or False :

post = "cant believe it... poor rabbits #simbah"
if "#simbah" in post:
    print("Contains the misspelled tag")

not in does the opposite.

Looping through a string. A for loop can visit each character in turn:

for ch in "Nimo":
    print(ch)

If you also need each character's position, loop over the indexes: for i in range(len(text)): and use text[i] . Loops like these let you build a new string one character at a time, using the accumulator pattern from Book 6 with a string that starts empty ( "" ).

Characters are numbers: ord() and chr() . In Book 6 you learned that every character has a code number (ASCII and Unicode). ord() gives a character's code; chr() gives the character for a code.

print(ord("A"), ord("a"), chr(77))

Output: 65 97 M . Capital letters A to Z are codes 65 to 90, so ord(letter) - ord("A") turns a capital letter into a number from 0 to 25: exactly what the Caesar formula needs.

Formatted output. f-strings (Book 6) can also line text up and round numbers. Inside the braces, after a colon: < means left-align, > right-align, ^ centre, a number sets the width, and .1f means one decimal place.

print(f"{'Name':<10}|{'Score':>6}")
print(f"{'Memoon':<10}|{95.456:>6.1f}")

Output:

Name      | Score
Memoon    |  95.5

A complete example: cleaning a post.

post = "  The Guardian SHOWS his true face! #Simbah  "
print(len(post))
clean = post.strip().lower()
print(clean)
print(clean.find("guardian"))
print(clean.count("a"))
print("#simbah" in clean)
print(clean.replace("#simbah", "#simbha"))

Output:

45
the guardian shows his true face! #simbah
4
4
True
the guardian shows his true face! #simbha

Notice post.strip().lower() : calling one method on the result of another is called method chaining. It reads left to right: strip first, then make lower case. Cleaning text into one standard form like this before searching it is called normalising the text, and it is the first step in almost every program that works with real-world writing, including the natural language processing you met in Book 6.

Career Spotlight: Data engineer. Real data is messy: extra spaces, mixed capitals, missing values, typing errors. Data engineers write programs that clean and organise data so that analysts and AI systems can use it. Most of their code looks a lot like the cleaning program above.

Illustration from Byte by Byte Book 7: Chapter 4 – Working with Strings

🛠️ Build It

Save all programs in Documents > Python Practice > Book 7.

Activity 1: String explorer. Type and run this, then predict the output before each line runs:

word = "SNOWPEAK"
print(word[0], word[3], word[-1], word[-2])
print(word[0:4], word[4:], word[:3], word[::2], word[::-1])

Now change word to your own name. Print the first letter, the last letter, the first three letters and your name backwards.

Activity 2: Caesar cipher program. Save as caesar.py . This version works with capital letters and leaves everything else (spaces, punctuation) unchanged.

message = input("Message (in CAPITALS): ")
key = int(input("Key (1-25): "))
mode = input("Encrypt or decrypt (e/d)? ").lower()
if mode == "d":
    key = -key
result = ""
for ch in message:
    if ch.isalpha():
        number = ord(ch) - ord("A")
        new_number = (number + key) % 26
        result = result + chr(new_number + ord("A"))
    else:
        result = result + ch
print("Result:", result)

Test it: decrypt the echo bird note SKDVH WZR: WKH PLUURU HQJLQH. PHHW DW WKH ROG PLOO. J with key 3. Then improve the program: add message = message.upper() after the first line so it also accepts small letters.

How it works: subtracting the key for decryption is the same as adding a negative key, and % 26 makes the alphabet wrap round in both directions, because Python's % always gives a result from 0 to 25 here, even for negative numbers.

Activity 3: Letter-frequency counter. Save as frequency.py . It draws a bar of # symbols for each letter that appears.

text = input("Paste the ciphertext: ").upper()
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for letter in alphabet:
    n = text.count(letter)
    if n > 0:
        print(f"{letter}: {'#' * n} {n}")

Run it on the echo bird note. You should see H: ####### 7 as the longest bar, with W: ##### 5 next.

Activity 4: Palindrome checker. A palindrome reads the same forwards and backwards, ignoring spaces, punctuation and capitals, like malayalam or Was it a car or a cat I saw.

phrase = input("Enter a word or phrase: ")
letters = ""
for ch in phrase.lower():
    if ch.isalpha():
        letters = letters + ch
if letters == letters[::-1]:
    print(f'"{phrase}" is a palindrome.')
else:
    print(f'"{phrase}" is not a palindrome.')

Activity 5: Passphrase strength meter. Write a program that asks for a passphrase and gives it a score: 2 points if it has 12 or more characters (or 1 point for 8 to 11), plus 1 point each for containing a digit, a capital letter, and a space or symbol. Print the score out of 5 and a message such as "Weak", "Okay" or "Strong". (Hint: loop through the characters and set True / False variables such as has_digit .) Test it with memoon (0), Skate2026 (3) and purple tiger dances at 7 pm! (4). Never test it with a real password you use.

Unplugged: Human slicer. Eight people stand in a line, each holding a card with one letter of a word. Everyone else calls out slices, like [2:5] or [::-1] or [-3:] , and the people in that slice step forward in order. Who gets it wrong most often: the people who forget to start at 0, or the people who forget that stop is not included?

✅ Case Closed

By midnight Memoon had a program that took any post, cleaned it, and checked it for words that mattered. She ran it on sample after sample from Beautine's records. Most of the posts were ordinary villagers: some angry, some upset, some saying clearly that the picture must be fake.

But one thing kept appearing. The tag #simbah .

"That's a spelling mistake," said Beautine, outraged. "His name has an H at the end, not an A-H."

"Exactly," said Memoon. "Real villagers spell it lots of different ways, or don't use a tag at all. But these posts all make the same mistake, written the same way." She ran .count("#simbah") over a long string of a hundred posts joined together. Thirty-eight of them. "Someone wrote one message with a typo, and a machine copied it again and again."

Vega was reading over her shoulder. "So the misspelling is like a fingerprint."

"A fingerprint," agreed Memoon. "But I've only checked a hundred posts, one string at a time. I need to hold all twelve thousand at once, sort them, count them and pick out every account that used it." She rubbed her eyes. "I need something bigger than a string."

❓ Test Yourself

  1. What is a string? Write three different ways to create one in Python.
  2. What is printed? (a) len("Pearlhaven") (b) "Na" * 4 (c) "Pebble" + " " +
"Hollow"
  1. For place = "RIVERBEND" , what are: (a) place[0] (b) place[-1] (c) place[2:5] (d) place[:5] (e) place[5:] (f) place[::-1] ?
  2. What does it mean that strings are immutable? How do you "change" a string?
  3. Which method would you use to: (a) remove spaces at both ends, (b) count how many times "the" appears, (c) check if a text contains only digits, (d) find the position of "@" in an email address?
  4. What does "Moonbrook".find("x") return, and why?
  5. What is the output of print("Hello\nWorld") ?
  6. What do ord("C") and chr(68) give?
  7. Encrypt PYTHON with a Caesar key of 5. Show the number for each letter.
  8. Fill in the blank: calling one method on the result of another, like text.strip().lower() , is called method ________.
  9. Challenge: Write a program that asks for a sentence and prints how many vowels it contains, how many words it has (hint: count the spaces, or use .split() and len() ), and the sentence with every vowel replaced by * .

📚 Key Terms

  • String: a sequence of characters, written inside quotation marks.
  • Concatenation: joining strings together with + .
  • Escape character: a backslash code such as \n for a special character inside a string.
  • Index: the position number of a character, counting from 0.
  • Negative index: a position counted from the end, where −1 is the last character.
  • Slice: part of a string, written [start:stop:step] ; stops just before stop .
  • Immutable: cannot be changed after it is created.
  • Method: a function that belongs to a type of data, called with a dot.
  • Method chaining: calling one method on the result of another.
  • Normalising: cleaning data into one standard form, such as lower case with no extra spaces.
  • ord() / chr() : functions that give a character's code number / the character for a code.
  • Palindrome: a word or phrase that reads the same forwards and backwards.

Keep learning with Byte by Byte

Explore Book 7: Networks, Programming and Machine Learning. Find the ebook, purchase details and teaching slides on MemuniCity.

Watch this chapter on YouTube

Comments

Popular posts from this blog

CA-7 Job Status and Failure Reason Codes

Here are the various status codes that You may see for jobs in the Queue or Logs in CA-7. R-C0002 R-C0003 R-C0099 R-C0255 R-JCLER A-U0002 A-U0004 A-U0015 A-U0043 A-U4095 A-SOC7 A-U4000 Reason Code/Job Status Code explanation: The indication of the job's current disposition. Values and their meanings are: A-Snnnn-- The job has failed with a system abend. A-Unnnn --The job has failed with a user abend. C-Cnnnn --The job has completed successfully and is going through completion processing. E-ARFATT-- An error occurred during the attempt to attach ARF definitions. This can result if the ARFSET specified is not defined. A diagnostic message may have been written to the CA-7 log, the OS console, or to the trailer queue for the job (in which case it can be displayed using LQ,JOB=x,LIST=ALL). E-ARFERR ---The job encountered an error in the ARF processing. Do a LARFQ command for the job to get more specific information. E-SEGERR --The job has been requeued...

Whistling Winds and Waterfalls: 4 Days of Magic in Shillong

Nestled in the clouds, where the scent of pine trees mingles with the rhythm of waterfalls and the tunes of local guitar-strumming youth—Shillong is more than a place. It’s a vibe. If you’ve got 3 nights and 4 days, you’ve got just enough time to fall in love. Here’s how to make the most of it—food, fun, fog and fantastic views included. Day 1: Shillong, We’re Coming for You! You land in Guwahati, barely out of the airport when the hills start calling. You hop into your cab, Spotify on, windows down, and the three-hour ride to Shillong begins. Just when you think it can’t get better, you stop at Umiam Lake —a lake so calm, it looks like someone ironed the water. By evening, you’re sipping hot chai in Laitumkhrah, maybe nibbling on spicy momos or pork jadoh from a roadside stall. You’re checked into your charming hotel ( Tripura Castle if you fancy old-world royalty, Ri Kynjai if you’re into lakeside poetry). The breeze whispers secrets of waterfalls and pine forests. Sleep well, drea...

Installing and Configuring Hadoop on Ubuntu as a Pseudo Distributed Single Node Cluster

Briefly what is psuedo-distributed single node Hadoop cluster: It is a Hadoop distributed cluster having Single Node. All the five daemons (NN,DN,JT,TT,SNN) are running as individual JVM (java process) instances. We will get all distributed features of Hadoop. This mode is used to develop, test, and staging (before production) Map Reduce programs quickly. It writes all the system, daemon and user logs to different files on the cluster To install Hadoop in this mode, we have to modify the hadoop-env.sh, core-site.xml, hdfs-site.xml, mapred-site.xml. hadoop-env.sh contains all the Environment variables which are required for running Hadoop. All the default values are fine, Only we have to modify the JAVA_HOME=“The location of Java Home Directory” Core-site.xml contains all the cluster specific information like io, temp directory, sorting, file system uri etc. Hdfs-site.xml contains all the parameters which are specific to HDFS like name node directory, data node directory...