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.
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
Turn capitals into small letters and small letters into capitals, leaving everything else alone — without swapcase().
# 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)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.
lAMBDAlABtEACHEScs
2Program 2 — replace every dash with a space
Replace every occurrence of one character with another — without replace().
# 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)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.
3Program 3 — capitalise the first letter of every word
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:
# 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)The Quick Brown Fox
new_word = TrueA 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.
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
Remove every repeated character, keeping the first of each. programming becomes progamin.
# 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)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.
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
Produce the sentence with no spaces in it, and report how many were removed.
# 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))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
Turn PYTHON into P-Y-T-H-O-N — a dash between every pair, and none hanging off the end.
# 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)P-Y-T-H-O-N
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
result = '' above the loop, result = result + something inside it. The original is untouched all the way through.
An if with no else quietly drops whatever failed the test. If a character is not being changed, add it unchanged.
The loop variable is wiped each round. Anything the program must remember lives above the loop — a counter, a collector or True/False.
swapcase, replace, title, join. Write the loop when the question asks for one, and the method when the code is yours.
- 1
Replace every vowel with a star, leaving the rest alone.
Hint · Program 2 with
ch.lower() in 'aeiou'as the test. - 2
Build a string of the digits of a sentence, in reverse order.
Hint · Collect with
result = ch + resultand the reversing comes free. - 3
Double every character:
catbecomesccaatt.Hint ·
result = result + ch + ch, orch * 2— replication works on a one-character string too. - 4
Capitalise every second letter of a word:
PyThOn.Hint · The index form, and a test on
i % 2. - 5
Remove every character that appears in a second string —
'programming'minus'gm'is'prorain'.Hint · One test —
ch not in unwanted— and noelse, because dropping is the job.
A swap-case program has an if for capitals and an elif for small letters, but no else. What happens to the spaces?
Why does the capitalise-each-word program need a variable outside the loop?
In the no-repeats program, what is seen doing?