Strings¶
Strings (of type str) are immutable iterables.
Each item in a string is a single text character, so a for loop steps through a string one character at a time.
for letter in "CIPHER":
print(letter, end=" ")
C I P H E R
Like a tuple or list, a string is ordered and supports indexing and slicing.
plaintext = "ENCRYPTION"
# Index: 0123456789
print(plaintext[0]) # First character.
print(plaintext[-1]) # Last character.
print(plaintext[2:7]) # Characters at indices 2 through 6 as a string.
E
N
CRYPT
Like tuples, but unlike lists, strings are immutable: the characters of a string cannot be changed after the string is created. In particular, characters cannot be reassigned through indexing.
plaintext[0] = "U"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[3], line 1
----> 1 plaintext[0] = "U"
TypeError: 'str' object does not support item assignment
Instead of modifying existing strings, new strings can be built from scratch in a few different ways.
String Operations¶
Adding two strings with + performs concatenation, creating a new string that contains the characters of the first operand followed by those of the second.
Multiplying a string by an integer with * performs duplication, repeating the string a given number of times.
s1 = "Hogwarts"
s2 = "hoggy woggy"
print(s1 + "school song") # Spaces are NOT added automatically!
print("-" * 19) # Repeat '-' 19 times, no spaces added.
print(s1 + " " + s1 + " " + s2 + " " + s1)
Hogwartsschool song
-------------------
Hogwarts Hogwarts hoggy woggy Hogwarts
Built-in functions for iterables, such as len(), max(), and min(), also work on strings.
Characters are ordered by their Unicode code point, the return value of the built-in function ord().
Letters are numbered consecutively from A to Z, with every uppercase letter coming before every lowercase letter.
word = "disproportionate"
print(len(word)) # Number of characters.
print(max(word)) # Character latest in the alphabet.
print(min(word)) # Character earliest in the alphabet.
16
t
a
Two strings can be compared with < or >, which compares the first characters from each string; if they are the same, then the second characters from each string are compared, and so on.
If one string is a prefix of the other, the shorter string comes first.
The == operator checks whether two strings contain the same characters in the same order.
print("Z" < "a") # Uppercase comes before lowercase.
print("apple" < "banana") # "a" comes before "b".
print("apple" > "avocado") # Compares "p" and "v".
print(sorted("Caesar")) # Sorts characters by code point.
True
True
False
['C', 'a', 'a', 'e', 'r', 's']
Quick Check
What is the output of the following code?
print(max("Julius"))
print(min("Julius"))
print("Zebra" < "aardvark")
Answer
u
J
True
"u"is the lowercase letter latest in the alphabet amongJ,u,l,i,u, ands."J"is the only uppercase letter, and every uppercase letter comes before every lowercase letter.The first characters
"Z"and"a"are compared first. Since"Z"is uppercase,"Z" < "a"and so"Zebra" < "aardvark".
String Methods¶
Like lists, strings have many useful methods, only a few of which are listed below.
In this table, s represents a string.
Method |
Description |
|---|---|
Return a copy of |
|
Return the number of non-overlapping occurrences of substring |
|
Return the lowest index in |
|
Return a string which is the concatenation of the strings in |
|
Return a copy of |
|
Return a copy of |
|
Return a list of the words in |
|
Return a list of the substrings in |
|
Return |
|
Return a copy of |
|
Return a copy of |
|
Return a titlecased version of |
|
Return a copy of |
s = "the Caesar cipher"
print(s.upper()) # Every letter uppercase.
print(s.lower()) # Every letter lowercase.
print(s.capitalize()) # First letter uppercase, all others lowercase.
print(s.title()) # First letter of each word uppercase.
print(s.swapcase()) # Every letter switches case.
print(s) # The original string is unchanged.
THE CAESAR CIPHER
the caesar cipher
The caesar cipher
The Caesar Cipher
THE cAESAR CIPHER
the Caesar cipher
Strings Are Immutable
List methods such as list.append() change the list itself, but string methods never change the string.
A common mistake is calling a string method without saving the result, which throws away the new string.
s = "lowercase"
s.upper()
print(s)
lowercase
To keep the result, assign it to a variable, as in s = s.upper().
print(s.count("e")) # "e" occurs three times.
print(s.index("C")) # "C" is at index 4.
print(s.index("cipher")) # "cipher" begins at index 11.
print(s.replace("Caesar", "shift")) # Replace a word.
print(s.replace("e", "3")) # Replace every "e".
3
4
11
the shift cipher
th3 Ca3sar ciph3r
The methods split() and join() perform complementary operations:
split()breaks a string into a list of substrings.join()combines an iterable of strings into a single string.
line = "How much wood would a woodchuck chuck"
words = line.split() # Split the string into a list of words.
print(words)
print("".join(words)) # Join a list of strings into one string.
print(" ".join(words)) # Join a list of strings into one string with spaces.
print("-".join(words)) # Join a list of strings into one hyphenated string.
['How', 'much', 'wood', 'would', 'a', 'woodchuck', 'chuck']
Howmuchwoodwouldawoodchuckchuck
How much wood would a woodchuck chuck
How-much-wood-would-a-woodchuck-chuck
Special Characters
A backslash \ inside a string can start an escape sequence, which represents a single special character.
Escape Sequence |
Character |
|---|---|
|
Newline |
|
Tab |
|
Single backslash |
|
Double quote |
|
Single quote |
Each escape sequence counts as one character, so len("A\tB") returns 3.
Spaces, tabs, and newlines are called whitespace characters.
With no arguments, split() separates a string at every run of whitespace.
In contrast, split(" ") uses each space as a delimiter, so consecutive spaces produce empty strings in the result.
text = "How much wood\nwould a\twoodchuck chuck"
print(text.split())
print(text.split(" "))
['How', 'much', 'wood', 'would', 'a', 'woodchuck', 'chuck']
['How', 'much', 'wood\nwould', 'a\twoodchuck', '', 'chuck']
Test Cases
The next two exercises use the following multi-line strings in the test cases.
seuss = """I am Sam. I am Sam. Sam I Am.
That Sam-I-am! That Sam-I-am! I do not like that Sam-I-am!
Would you like green eggs and ham?
I do not like them, Sam-I-am.
I do not like green eggs and ham."""
henryV = """What's he that wishes so?
My cousin Westmoreland? No, my fair cousin:
If we are mark'd to die, we are enow
To do our country loss; and if to live,
The fewer men, the greater share of honour.
God's will! I pray thee, wish not one man more.
By Jove, I am not covetous for gold,
Nor care I who doth feed upon my cost;
It yearns me not if men my garments wear;
Such outward things dwell not in my desires:
But if it be a sin to covet honour,
I am the most offending soul alive.
No, faith, my coz, wish not a man from England:
God's peace! I would not lose so great an honour
As one man more, methinks, would share from me
For the best hope I have. O, do not wish one more!
Rather proclaim it, Westmoreland, through my host,
That he which hath no stomach to this fight,
Let him depart; his passport shall be made
And crowns for convoy put into his purse:
We would not die in that man's company
That fears his fellowship to die with us.
This day is called the feast of Crispian:
He that outlives this day, and comes safe home,
Will stand a tip-toe when the day is named,
And rouse him at the name of Crispian.
He that shall live this day, and see old age,
Will yearly on the vigil feast his neighbours,
And say 'To-morrow is Saint Crispian:'
Then will he strip his sleeve and show his scars.
And say 'These wounds I had on Crispin's day.'
Old men forget: yet all shall be forgot,
But he'll remember with advantages
What feats he did that day: then shall our names.
Familiar in his mouth as household words
Harry the king, Bedford and Exeter,
Warwick and Talbot, Salisbury and Gloucester,
Be in their flowing cups freshly remember'd.
This story shall the good man teach his son;
And Crispin Crispian shall ne'er go by,
From this day to the ending of the world,
But we in it shall be remember'd;
We few, we happy few, we band of brothers;
For he to-day that sheds his blood with me
Shall be my brother; be he ne'er so vile,
This day shall gentle his condition:
And gentlemen in England now a-bed
Shall think themselves accursed they were not here,
And hold their manhoods cheap whiles any speaks
That fought with us upon Saint Crispin's day."""
Problem 1
Write a function named wordcount() that accepts a single string.
Compute the following statistics about the string:
The total number of characters.
The number of words, where words are separated by whitespace (spaces, tabs, or newlines).
The average word length. Punctuation counts toward the length of a word, so
"Hi!"has length 3.The length of the longest word.
Return all four values, in the order listed. You may assume that the input contains at least one word.
Hint: A list comprehension may be useful.
Test Cases
print(wordcount("A B C D E F G"))
print(wordcount("A B C D\nE\tF G"))
(13, 7, 1.0, 1)
(13, 7, 1.0, 1)
print(wordcount(seuss))
print(wordcount(henryV))
(187, 40, 3.7, 9)
(2133, 408, 4.230392156862745, 13)
Problem 2
Write a function named redact() that accepts a string (the message) and a list of strings (the blacklist).
For each string in the blacklist, replace every occurrence of that string in the message with asterisks, using one * for each character (for example, "eat" becomes "***").
Return the redacted message.
Test Cases
blacked = ["eat", "sleep", "study"]
print(redact("Your secret orders are to eat, read, and sleep.", blacked))
print(redact("Is it more important to study or to sleep?", blacked))
Your secret orders are to ***, read, and *****.
Is it more important to ***** or to *****?
print(redact(seuss, ["not", "green"]))
I am Sam. I am Sam. Sam I Am.
That Sam-I-am! That Sam-I-am! I do *** like that Sam-I-am!
Would you like ***** eggs and ham?
I do *** like them, Sam-I-am.
I do *** like ***** eggs and ham.
print(redact(seuss, "aeiouAEIOU")) # Redact every vowel.
* *m S*m. * *m S*m. S*m * *m.
Th*t S*m-*-*m! Th*t S*m-*-*m! * d* n*t l*k* th*t S*m-*-*m!
W**ld y** l*k* gr**n *ggs *nd h*m?
* d* n*t l*k* th*m, S*m-*-*m.
* d* n*t l*k* gr**n *ggs *nd h*m.