MathubLearn / Practice / Excel
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

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)   # unchanged
Output
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

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.