CSCI 127 Joy and Beauty of Data · Unit 1: Data types · on Exam 1
1.5 Strings
Study notes for Strings in CSCI 127 Joy and Beauty of Data at Montana State University: the big ideas, code you should know, a worked example, common mistakes and an exam tip. The same topic has endless practice questions and flashcards in Mathub.
Big ideas
- A string is a sequence of characters. Index from 0:
s[0]is the first character,s[-1]the last,len(s)the length. - Slices copy a piece:
s[a:b]is characters a up to but not including b; leave out an end to go to the edge;s[::-1]reverses. - Strings are immutable: methods give back a new string.
upper() lower() strip() replace(a, b) split() find(x) count(x) startswith(x) isdigit(). Use", ".join(list)to glue pieces. +joins,*repeats,intests for a substring, and afor ch in sloop visits each character.- Escape sequences:
\nnewline,\ttab,\"a quote.ord("A")is 65 andchr(66)is "B".
Code you should know
Indexing and slicing
s = "Bobcats"
print(s[0], s[-1], len(s))
print(s[0:3], s[3:], s[:3], s[::-1])
print(s[1:6:2])Output
B s 7 Bob cats Bob stacboB obas
Methods return new strings
line = " Go Cats, go! "
clean = line.strip()
print(clean.upper())
print(clean.lower().count("go"))
print(clean.replace("Cats", "Bobcats"))
words = clean.split()
print(words, len(words))
print("-".join(words))
print(line) # unchangedOutput
GO CATS, GO! 2 Go Bobcats, go! ['Go', 'Cats,', 'go!'] 3 Go-Cats,-go! Go Cats, go!
Counting vowels with a loop
text = input("Text: ")
vowels = 0
for ch in text.lower():
if ch in "aeiou":
vowels += 1
print(f"{vowels} vowels in {len(text)} characters")Output
5 vowels in 15 characters
Worked example
With
s = "python", what are s[2:5], s[-2:], s.upper()[0] and s * 2?Show the solution
"tho" (indexes 2, 3, 4), "on" (last two), "P", and "pythonpython".Common mistakes
- Expecting
s.upper()to changes. Assign the result:s = s.upper(). - Off-by-one in slices:
s[1:3]has two characters, not three. s[len(s)]is an IndexError; the last index islen(s) - 1.- Comparing a digit string to a number:
"7" == 7is False.
Exam tipDraw the index ruler under the string (0, 1, 2, … and −1, −2 from the right) before answering any slice question.
Keep going in Mathub
Mathub is free for Montana State students: an endless quizzer with worked explanations, one-question lessons, flashcards, exam prep checklists, the class calendar with every deadline, a grade calculator and a study board for CSCI 127.