Building new text
Make a new string one piece at a time, with separators in the right places. About 9 minutes.
Start with nothing, add pieces
To build a new piece of text, start with an empty string, which is just a pair of quotes with nothing between. It is like a blank page. Then add to it, one piece at a time, with a loop.
In each pass, glue the next piece onto the end of the string. When the loop finishes, the page is full and you return it. You never change the original text. You are writing a fresh copy, with your own changes in it.
result = ""
for ch in s:
result = result + chSeparators go between
Say you want to spread a word out with spaces, so that "abc" becomes "a b c". It is tempting to add a space after every letter. But then the result ends with a space too: "a b c ". That is wrong.
A space belongs between the letters, not after the last one. The trick: before you add a letter, check whether the result is still empty. If it isn't, add the space first. The very first letter then gets no space.
result = ""
for ch in s:
if result != "":
result = result + " "
result = result + ch- result
- a
The result starts empty. For the first letter, the result is empty, so no space is added first. Just add a.
You spread out the word "hi" with a single space between letters. How many characters does the result have?
- A3
- B4
- C2
Show the answer
3. h, a space and i make three characters.
Spread it out
Return the text with a single space between each pair of letters. There should be no space before the first letter or after the last. An empty text stays empty.
s = "abc" → "a b c"
0 ≤ length of s ≤ 1,000 · lowercase letters only