Strings
Contents
Strings#
An ordered collection of characters accessed via index numbers.
- Type
str
- Synatx
"char,..."
- Bases
Sequence, Iterable
- State
Immutable
- Position
Ordered
- Composition
Homogeneous
- Diversity
Repeatable
- Access
Subscriptable
- Value
Hashable
Part 1: Introduction#
While most of the time we can think of strings as text data, under the hood strings are a sequence of characters.
Part 1.1: Creating#
Strings store text data and can be enclosed in either single or double quotes.
""
"Hello."
'Farewell.'
"It's a lovely day."
'"Well hello!", he said.'
'"Well hello!", he said.'
For a string that spans multiple lines, enclose it in triple double ("""
) or
triple single ('''
) quotes.
rhyme = """Roses are red,
Violets are blue,
Sugar is sweet,
And so are you."""
print(rhyme)
Roses are red,
Violets are blue,
Sugar is sweet,
And so are you.
Backslashes (\
) are used to escape quotes or to indicate special characters,
like \n
for a new line.
print('It\'s a nice day.')
print("line one\nline two")
It's a nice day.
line one
line two
For strings that contain backslashes use a double backslash (\\
) or prefix
the string with the letter r
for a raw string.
print('"\\n" is used to add a newline')
print(r"C:\Documents\nodes")
"\n" is used to add a newline
C:\Documents\nodes
Part 1.2: Exercises#
(String Creation)
Use a docstring to split the lymric or lullaby of your choice into a multi-line string and assign it to the variable
verse
, then print it.Using one double-string or single-quoted string, print the words
"one"
,"two"
, and"three"
on three seperate lines.Print a double quoted string that includes double quotes. Print a single quoted string that includes single quotes.
Print a string that includes backslashes by escaping the backslash. Print a second string that includes backslashes using an r-string.
Solution to Exercise 58 (String Creation)
#1: Verse Docstring
1verse = """Jack and Jill
2Went up the hill
3To fetch a pail of water
4Jack fell down and broke his crown
5And Jill came tumbling after."""
6
7print(verse)
#2: One, Two, Three lines, muah hah haa!
1print("one\ntwo\nthree")
#3: Quotable quotes
1print('...for he\'s a jolly good fellow, that nobody can deny!')
2print("She muttered, \"Well, I for one can deny it.\"")
#4: Sometimes backslashes just want to be seen
1print('This is a backslash: "\\".')
2print(r'So is this: "\".')
Part 1.2: Modifying#
Strings are immutable, which means that once created, they cannot be changed. But it’s only the exact object stored in memory that can’t be changed. Most of the time, we don’t care so much about the exact object, just the end result.
What you can do is create a new string cobbled together from the parts of other strings, and you can even assign it back to the same variable name.
Strings can be concatenated (joined together) by using
the +
operator.
name = "coding class"
print("Welcome to " + name + ".")
Welcome to coding class.
String literals (the ones in quotes) next to each other are automatically concatenated.
text = "Today we're talking about" 'strings.'
print(text)
Today we're talking aboutstrings.
You can take advantage of this to break long text into
multiple lines of code. Put strings on consecutive lines
without separating commas and enclose the whole expression
in parentheses (
)
.
text = (
"Lorem ipsum dolor sit amet, consectetur "
"adipiscing elit, sed do eiusmod tempor "
"incididunt ut labore et dolore magna "
"aliqua. Ut enim ad minim veniam, quis "
"nostrud exercitation ullamco laboris "
"nisi ut aliquip ex ea commodo consequat."
)
print(text)
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
To effectively append to an existing string, you can use the +=
operator.
text = "Unfinished "
text += "business."
print(text)
Unfinished business.
You can repeat a string multiple times using the *
operator.
text = "The horror! " * 2
print(text)
The horror! The horror!
Similarly you can use the *=
operator to effectively append a value to itself
a number of times.
text = "All work and no play makes Jack a dull boy.\n"
text *= 5
print(text)
All work and no play makes Jack a dull boy.
All work and no play makes Jack a dull boy.
All work and no play makes Jack a dull boy.
All work and no play makes Jack a dull boy.
All work and no play makes Jack a dull boy.
Use an f-string for string interpolation by prefixing the string with the
letter f
then enclose the variable or other evaluated code curly braces ({
}
).
price = 1.25
count = 5
print(f"I am buying {count} apples for ${price} each.")
print(f"The total is ${price*count}.")
I am buying 5 apples for $1.25 each.
The total is $6.25.
Part 1.2: Exercise#
(String Modification)
Use the
+
operator to join two strings together and print the result.Concatonate two string literals without using the
+
operator and print the result.Choose a long paragraph of text. Break it up onto multiple lines in your code while still all on one line in the string itself. Assign it to the variable
paragraph
and print it.Assign the string
"Four out of five dentists agree: "
to the varabletext
. Choose something the dentists agree on and on a new line, append it totext
. Printtext
.Use both the
+
and*
operators to assign the string"Noooooo!"
to the variabletext
then print it. Change the number of"o"
s and print it again.Pick something that Bart Simpson may have written on the blackboard and assign it to the variable
admonition
. Append it to itself10
times then print it.
Note: This should take no more than 2 lines of code. Bonus: Write a function to do this.Choose a name and assign it to the variable
name
. Using an f-string, print:
"Hello my name is: NAME."
Create a visual line by repeating the underscore character (
"_"
) some number of times, (say,20
) and assign it to the variableline
. Using an f-string, make a string with a single line of a sign-up sheet that looks something like this:"Name: ____________________ Email: ____________________"
Assign it to the variable
row
and print it25
times to generate a sign-up sheet.
Solution to Exercise 59 (String Modification)
#1: Concatonate with +
1text = "Hello " + "world!"
2print(text)
#2: Concatonate without an operator
1text = "Goodbye " "cruel world!"
2print(text)
#3: Paragraph concatonation
1paragraph = (
2 "Quo usque tandem abutere, Catilina, "
3 "patientia nostra? Quam diu etiam "
4 "furor iste tuus nos eludet? Quem "
5 "ad finem sese effrenata iactabit "
6 "audacia?"
7)
8print(paragraph)
#4: Dentists conclude…
1text = "Four out of five dentists agree: "
2text += "that other guy is nuts."
3print(text)
#5a: Variously emphatic "No!"
1text = "N" + ("o"*1) + "!"
2print(text)
3
4text = "N" + ("o"*3) + "!"
5print(text)
6
7text = "N" + ("o"*8) + "!"
8print(text)
#5b: (Bonus) Efficient variously emphatic "No!"
1def no(ohs):
2 text = "N" + ("o"*ohs) + "!"
3 print(text)
4
5no(1)
6no(3)
7no(8)
#6: Chalkboard repetition
1admonition = "I will not repeat myself.\n"
2admonition *= 10
3print(admonition)
#7: Nametag
1name = "Inigo Montoya"
2print(f"Hello my name is: {name}.")
#8: Sign-up Sheet
1line = "_" * 20
2row = f"Name: {line} Email: {line}\n"
3print(row * 25)
Part 2: Splitting and Joining#
We often want to split a string apart in various ways, or create a string from a list of strings. In other words, to convert a string to a list and vice versa.
Part 2.1: Converting to and from lists#
The most common way to split a string is using the .split()
method. With no
arguments, it splits the string on any whitespace.
name = "Jean-Claude Van Damme"
name.split()
['Jean-Claude', 'Van', 'Damme']
If you pass an argument to .split()
, it will use that character or substring
as the delimiter, instead of whitespace.
phone = "555-867-5309"
phone.split("-")
['555', '867', '5309']
text = "one and two and three and four"
text.split(" and ")
['one', 'two', 'three', 'four']
Or if you want a list where each character is an element call list()
.
text = "apart"
list(text)
['a', 'p', 'a', 'r', 't']
To convert a list (or other iterable) to a string, use the str.join()
method.
letters = ['t', 'o', 'g', 'e', 't', 'h', 'e', 'r']
"".join(letters)
'together'
shapes = ["triangle", "square", "circle"]
", ".join(shapes)
'triangle, square, circle'
Part 2.1: Exercises#
(Splitting and Joining Exercise)
Take the quote of your choice and assign it to the variable
quote
. Split it into a list of words (seperated by whitespace) and print the result.Assign this string to the variable
flavors
:
"banana split;hot fudge;cherry;malted;black and white"
Split it into a list on the deliter";"
.Look up the word of the day and assign it to the variable
word
. Convert it to a list of characters and print it.Make a list with every letter in the current day of the week and assign it to the variable
day
. Turn it into a string (join it using a blank string as the delimiter) and print it.Make a list of three
dinosaurs
. Join it on a newline delimiter then print it.
Solution to Exercise 60 (Splitting and Joining Exercise)
#1: Quote words
1quote = "Life is what happens when you're busy making other plans."
2print(quote.split())
#2: Flavors
1flavors = "banana split;hot fudge;cherry;malted;black and white"
2print(flavors.split(";"))
#3: Letters of the Day
1word = "treacle"
2print(list(word))
#4: Day Letters to Word
1day = ['T', 'u', 'e', 's', 'd', 'a', 'y']
2print("".join(day))
#5: Dinosaurs
1dinosaurs = ["Tyrannosaurus Rex", "Stegosaurus", "Velociraptor"]
2print("\n".join(dinosaurs))
Part 3: Strings as sequences#
Under the hood a string is a sequence of characters. Let’s take a simple example.
word = "cat"
This could be visualized as:
Part 3.1: Sequence features#
Since it is a sequence, that means you can do most of the same things you can do with a list.
You can use subscription
to access characters via negative or positive index
number.
print(word[0])
print(word[-1])
c
t
You can get part of a string via slice.
print(word[1:])
at
You can get the length using the len()
function.
len(word)
3
You can check if a single character or a substring is part of a string using
the in
and not in
operators.
"c" in word
True
"at" not in word
False
You can check how many times a letter or substring occurs in a string using the .count()
method.
word.count("c")
1
word.count("at")
1
You can find out the index number of the first occurrence of a letter or substring.
word.index("c")
0
word.index("at")
1
You can iterate over every character.
for char in word:
print(char)
c
a
t
However, since strings are immutable, you cannot modify a string via subscription.
word[0] = "b"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[29], line 1
----> 1 word[0] = "b"
TypeError: 'str' object does not support item assignment
Part 3.2: Exercises#
(String as Sequence Exercise)
Make a list of words and assign it to the variable
sentence
. Iterate over the list and print the first letter in each word.
Solution to Exercise 61 (String as Sequence Exercise)
1sentence = ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog.']
2
3for word in sentence:
4 print(word[0])