LambdaLabTM
Computer Science · Class 11 · Strings Revisited
ProgramsBuilding⏱️ 16 min read

Building a New String

A string cannot be edited, so every program that seems to change one is really building a second string next to it. The shape never varies: an empty collector above the loop, one decision per character inside it, and a name pointed at the result. Each program here also has a method that would do the whole job — and the loop is what the question is asking for.

Key Takeaway
Every character has to be dealt with. The commonest fault on this page is a loop with an if and no else: the characters that fail the test are silently thrown away, and the result comes out short. If a character is not being changed, it still has to be added unchanged.

1Program 1 — swap the case of every letter

📋 The problem

Turn capitals into small letters and small letters into capitals, leaving everything else alone — without swapcase().

swap_case.py
# swap the case of every letter, without swapcase()

sentence = 'LambdaLab Teaches CS'
swapped = ''

for ch in sentence:
    if ch.isupper():
        swapped = swapped + ch.lower()
    elif ch.islower():
        swapped = swapped + ch.upper()
    else:
        swapped = swapped + ch

print(swapped)
Output
lAMBDAlAB tEACHES cs
else:

The branch that does nothing except keep the character. Delete it and the spaces vanish — the output becomes lAMBDAlABtEACHEScs, with no error to say so.

swapped = swapped + ch.lower()

ch.lower() hands back a new one-character string; ch is untouched, and so is sentence. Only swapped changes, and it changes by being pointed at a longer string each round.

swap_case.py — with the else branch deleted
Output
lAMBDAlABtEACHEScs

2Program 2 — replace every dash with a space

📋 The problem

Replace every occurrence of one character with another — without replace().

swap_char.py
# replace every occurrence of one character, without replace()

sentence = 'a-b-c-d-e'
old = '-'
new = ' '
changed = ''

for ch in sentence:
    if ch == old:
        changed = changed + new
    else:
        changed = changed + ch

print(changed)
Output
a b c d e

Two branches, and both add exactly one character — which is why the result is the same length as the original. Putting the two characters in named variables is what turns a one-off program into one that answers “replace any character with any other”: change the two lines at the top and nothing else.

swap_char.py

3Program 3 — capitalise the first letter of every word

📋 The problem

Turn the quick brown fox into The Quick Brown Fox — without title().

This one needs something the others do not: memory of where you are. A character has no idea whether it begins a word, so the program has to remember whether the last character was a space:

title_case.py
# capitalise the first letter of every word, without title()

sentence = 'the quick brown fox'
result = ''
new_word = True

for ch in sentence:
    if new_word and ch != ' ':
        result = result + ch.upper()
        new_word = False
    else:
        result = result + ch

    if ch == ' ':
        new_word = True

print(result)
Output
The Quick Brown Fox
new_word = True

A flag, started above the loop. True means 'the next letter begins a word'. It starts True because the very first letter does.

if new_word and ch != ' ':

Two conditions: we are expecting a first letter, and this is not a space. The second half matters for a sentence with two spaces in it — the flag must not be spent on a space.

if ch == ' ':

At the end of the body, at loop level, so it runs whichever branch was taken. A space means the next letter starts a word.

Key Takeaway
A flag is how a loop remembers. The loop variable is wiped every round, so anything the program must carry from one round to the next lives in a variable created above the loop — a counter, a collector, or a True/False flag like this one. Same idea as the “all digits” check on the previous page.

4Program 4 — keep only the first appearance of each character

📋 The problem

Remove every repeated character, keeping the first of each. programming becomes progamin.

no_repeats.py
# keep only the first appearance of each character

word = 'programming'
seen = ''

for ch in word:
    if ch not in seen:
        seen = seen + ch

print('Without repeats:', seen)
Output
Without repeats: progamin

The collector is doing two jobs at once, which is what makes this program short: seen is both the answer being built and the record of what has already been met. The test ch not in seen asks the half-built answer whether it has had this character before.

Watch Out
not in is one operator, not a not and an in to be arranged. if ch not in seen: reads as English and is the normal spelling. if not ch in seen: means the same thing here and is worth avoiding, because it reads as though the not applies to ch.

5Program 5 — remove the spaces

📋 The problem

Produce the sentence with no spaces in it, and report how many were removed.

no_spaces.py
# take the spaces out of a sentence

sentence = input('Enter a sentence: ')
tight = ''

for ch in sentence:
    if ch != ' ':
        tight = tight + ch

print('Without spaces:', tight)
print('Characters removed:', len(sentence) - len(tight))
Output
Enter a sentence: a b c d e
Without spaces: abcde
Characters removed: 4

This is the one program on the page where the missing else is correct — dropping characters is the whole job. And the count of what was removed needs no counter: it is the difference between the two lengths, worked out after the loop.

6Program 6 — put a dash between the characters

📋 The problem

Turn PYTHON into P-Y-T-H-O-N — a dash between every pair, and none hanging off the end.

dashes.py
# put a dash between every pair of characters

word = 'PYTHON'
spaced = ''

for i in range(len(word)):
    spaced = spaced + word[i]

    if i < len(word) - 1:
        spaced = spaced + '-'

print(spaced)
Output
P-Y-T-H-O-N
Key Takeaway
“Between” is a fence-post question. Six characters have five gaps between them, so the dash must be skipped on the last round — which needs to know which round it is, and that is why this program uses the index form. The lazy version adds a dash after every character and then removes the last one with spaced[:-1]; both are fine, and the if version says what it means.

Python does this in one call: '-'.join(word) gives 'P-Y-T-H-O-N', and join() was built for exactly the fence-post problem.

7Recap

Strings are built, never edited

result = '' above the loop, result = result + something inside it. The original is untouched all the way through.

Deal with every character

An if with no else quietly drops whatever failed the test. If a character is not being changed, add it unchanged.

A flag carries news between rounds

The loop variable is wiped each round. Anything the program must remember lives above the loop — a counter, a collector or True/False.

Know the method it replaces

swapcase, replace, title, join. Write the loop when the question asks for one, and the method when the code is yours.

✍️ Now write these yourself
  1. 1

    Replace every vowel with a star, leaving the rest alone.

    Hint · Program 2 with ch.lower() in 'aeiou' as the test.

  2. 2

    Build a string of the digits of a sentence, in reverse order.

    Hint · Collect with result = ch + result and the reversing comes free.

  3. 3

    Double every character: cat becomes ccaatt.

    Hint · result = result + ch + ch, or ch * 2 — replication works on a one-character string too.

  4. 4

    Capitalise every second letter of a word: PyThOn.

    Hint · The index form, and a test on i % 2.

  5. 5

    Remove every character that appears in a second string — 'programming' minus 'gm' is 'prorain'.

    Hint · One test — ch not in unwanted — and no else, because dropping is the job.

Quick Check

A swap-case program has an if for capitals and an elif for small letters, but no else. What happens to the spaces?

Quick Check

Why does the capitalise-each-word program need a variable outside the loop?

Quick Check

In the no-repeats program, what is seen doing?