3.4 StringsJoining and cutting text

A string is an ordered sequence of characters, written in quotes: "Hello", "B-12", "42". The quotes matter. "42" is a string of two characters, not the number 42, so you can't do arithmetic with it.
String concatenation joins two or more strings end to end to make a new string. A substring is part of an existing string. The reference sheet doesn't define procedures for these, so each exam question that uses them defines its own, for example concat(a, b), which returns b joined to the end of a, and substring(str, start, length), which returns length characters of str beginning at position start.
?Wait, why does position start at 1? Python starts at 0.
Concatenation adds nothing between the strings: concat("sun", "day") is "sunday", with no space. If you want a space, you have to concatenate one: concat(concat("sun", " "), "day"). And concatenating number-looking strings just puts the characters side by side: concat("4", "2") is "42", not 6.
1first ← "Jordan"2last ← "Okafor"3user ← concat(substring(last, 1, 4), substring(first, 1, 1))14user ← concat(user, "26")25DISPLAY(user)
- line 3 "Okaf" joined to "J"
- line 4 The string "26" goes on the end
| expression | value |
|---|---|
| substring(last, 1, 4) | "Okaf" |
| substring(first, 1, 1) | "J" |
| user after line 3 | "OkafJ" |
| user after line 4 | "OkafJ26" |
?Wait, what do nested calls like concat(substring(...), ...) mean?
I thought about it. Show me
concat(a, b) joins b to the end of a, and substring(str, start, length) returns length characters starting at position start, where position 1 is the first character. What is displayed?
day ← "saturday" DISPLAY(concat(substring(day, 1, 3), substring(day, 6, 3)))
- Number the letters: s1 a2 t3 u4 r5 d6 a7 y8.
Why?
Writing the positions down prevents off-by-one mistakes. - substring(day, 1, 3) is positions 1 to 3: "sat".
- substring(day, 6, 3) is positions 6, 7, 8: "day".
- concat("sat", "day") is "satday", with nothing in between.
Answer: satday
Stuck? Get a hint
- Write the position number under each letter of "saturday".
- Three characters starting at 6 means positions 6, 7 and 8.
- concat puts its first argument first.
- A"notebook"
- B"booknote"
- C"ebooknot"
- D"book note"
Show the answer
B. Positions 5 to 8 of "notebook" are "book", and positions 1 to 4 are "note". concat puts the first argument first: "booknote". Choice C counts from 0, and D adds a space concat never adds.
- A string is an ordered sequence of characters in quotes. "42" is text, not a number.
- Concatenation joins strings end to end, adding nothing between them.
- A substring is part of a string. Exam questions define their own string procedures.
- Count string positions from 1, and evaluate nested calls from the inside out.