Strings

We have encountered strings already. Remember our "Hello World!" program?


In [ ]:
print("Hello World!")

"Hello World!" was the string. Absolutely any character can be a string, including numbers, as long as they are within single, double, or triple quotation marks.


In [ ]:
str01 = "Hello World!"
str02 = "22"
str03 = "This is so c00l!"
print(str01, str02, str03)

In [ ]:
print(type(str02))

Now remember how we converted an int to a float, and vice versa?


In [ ]:
children = 5

In [ ]:
type(children)

In [ ]:
new_children = float(children)
type(new_children)

You can convert them to strings too!


In [ ]:
stringy_kids = str(children)
type(stringy_kids)

Switching between Single, Double and Triple Quotes

Text = The name's Bond, James Bond.


In [ ]:
text01 = "The name's Bond, James Bond."

In [ ]:
print(text01)

In [ ]:
text02 = """The name's Bond, James Bond."""
text03 = """Text here"""
text04 = """Here we go!"""

In [ ]:
print(text02)
print(text03)
print(text04)

In [ ]:
text05 = 'The name's Bond, James Bond.'
print(text05)

Say hello to escape characteters!


In [ ]:
text05 = 'The name\'s Bond, James Bond.'

In [ ]:
print(text05)

In [ ]:
text06 = 'The name\'s Bond, James Bond.\nYes really!'
print(text06)

In [ ]:
text07 = 'The name\'s Bond, Tabbed Bond.\tYes really!'
print(text07)
text08 = "The name\'s Bond, Tabbed Bond.   Yes really!"
print(text08)

"Raw" Strings

What if a character like a backslash () is part of a string?


In [ ]:
print("Please Access C:\home\test instead of C:\\games\n\hello")

In [ ]:
print(r"Please Access C:\home\test instead of C:\\games\n\hello")

String Substitution


In [ ]:
age = 42
print("I am {} years old.".format(age))

In [ ]:
print("I am {} years old".format(age))
print("Hello World!")

Did you see above how we used .format to substitute a string? This is so useful when writing more complex functions with strings. Let's see another example.


In [ ]:
fighter1 = input()
fighter2 = input()

In [ ]:
type(fighter1)

In [ ]:
print("We went to see a bout between {} and {}. {} totally kicked ass!".format(fighter1,fighter2, fighter1))

Indexing Strings

This is a very important topic!
Indexing and slicing form the basis of a lot of data manipulation techniques, so make sure you spend a lot of time practicing this.

Example 1: Indexing always begins at 0. Do you see why the answer here is "k"?

Example 2: Indexing can have a lower bound, and an upper bound. The lower bound is always inclusive, and the upper bound is always exclusive.

Example 3: Similarly, -1 would imply the very last character. -2 would imply the 2nd last character, and so on.

Example 4: Again, the upper bound is exclusive. Always!

Example 5: You can skip strings too. The format? [Lower Bound : Upper Bound : Character-to-Skip]

Example 6 : You can also index all character.

Example 7 : Index all character, and then skip every 2 (or 3 or 4 as you wish).

Example 8 : Reversing strings


In [5]:
show = 'Monty Python'

In [2]:
show[0]


Out[2]:
'M'

In [3]:
show[-1]


Out[3]:
'n'

In [4]:
show[0:4]


Out[4]:
'Mont'

In [6]:
show[0:5]


Out[6]:
'Monty'

In [7]:
show[-7:]


Out[7]:
' Python'

In [8]:
show[-3:]


Out[8]:
'hon'

In [9]:
show[1:]


Out[9]:
'onty Python'

Exercise

  • create a string named 'Welcome to the Jungle'
  • print the word 'Welcome' using indexing
  • print the word 'Jungle' using negative indexing
  • print the phrase 'come to the Jungle' using slicing

In [ ]:
# Enter your code below:

String Operations

  • + : concatenate two (or more) strings
  • len(string): find the number of characters ina string
  • string.upper(): returns an uppercase version of a string
  • string.lower(): returns a lowercase version of a string
  • haystack.find(needle): searches haystack for needle, prints the position of the first occurrence, indexed from 0. Returns -1 if not found
  • string_1.count(string_2): counts the number of occurrences of one string in another.
  • haystack.startswith(needle): does a the haystack string start with the needle string?
  • haystack.endswith(needle): does a the haystack string end with the needle string?
  • string_1.split(string_2): split the first string at every occurrence of the second string. Outputs a list (see below).
  • ==: are the two operand strings the same?
  • string.strip(): remove any whitespace from the left or right of the string, including newlines.

Read more about string operations here: https://docs.python.org/3/library/string.html


In [ ]:
sherlocked = "To Sherlock Holmes she is always the woman."
print(sherlocked)

In [ ]:
print(len(sherlocked))

In [ ]:
print(sherlocked.upper())

In [ ]:
print(sherlocked.lower())

In [ ]:
sherlocked.find("she")

Like most things in Python, we can assign that to a variable


In [ ]:
pronoun = sherlocked.find("she")
print(pronoun)

In [ ]:
# Where can we find the first occurance of 'she'?
print("The world 'she' first appears at index", pronoun)

In [ ]:
watson = "In the year 1878 I took my degree of Doctor of Medicine of the University of London, and proceeded to Netley to go through the course prescribed for surgeons in the army. Having completed my studies there, I was duly attached to the Fifth Northumberland Fusiliers as Assistant Surgeon. The regiment was stationed in India at the time, and before I could join it, the second Afghan war had broken out. On landing at Bombay, I learned that my corps had advanced through the passes, and was already deep in the enemy’s country. I followed, however, with many other officers who were in the same situation as myself, and succeeded in reaching Candahar in safety, where I found my regiment, and at once entered upon my new duties."

In [ ]:
print(watson)

In [ ]:
first_appearance = watson.find("my")
first_appearance

In [ ]:
second_appearance = watson.find("my", first_appearance + 1)
second_appearance

In [ ]:
watson.count("on")

Exercise

Find out how many times the word "the" occurs.


In [ ]:

Exercise

Find the midpoint of the passage. Is there a difference in the occurrence of the word 'the' in the first half, versus the second half?

(Hint: The midpoint would be int(len(watson)/2). Why int? Because practically speaking, 104.5 being the midpoint is meaningless. Converting to int means you have a whole number.)

Splitting Strings


In [ ]:
print("A Study in Scarlet".split(" "))

In [ ]:
watson.count("me")

In [ ]:
watson.startswith("Sherlock")

In [ ]:
watson.endswith("duties.")

In [ ]:
watson.split("and")

In [ ]:
watson2 = "    Hello    "

In [ ]:
watson2.strip()

In [ ]:
watson3 = watson.replace(",","")
watson3 = watson3.replace(".", "")
watson3

In [ ]:
watson3.split(" ")

More Splits


In [ ]:
ice_cream = "chocolate vanilla banana caramel"
ice_cream = ice_cream.split(" ")
print(ice_cream)

In [ ]:
ice_cream[0]

In [ ]:
ice_cream[-1]

In [ ]:
ice_cream[1]

In [ ]:
len(ice_cream)

Exercise

Create a progam to take an email as an input, and print the username and domain as outputs.

Example: gavin@hooley.com should return

  • Username: gavin
  • Domain: hooley.com

Hint: Use the .split method, then use indexing. This is not something we have covered in great detail, but think of it as a challenge. The answer is provided at the end of this notebook.


In [ ]:
# gavin@hooley.com

Exercise

  • How many times does the name "Sherlock" appear in the passage below?
  • How many times does the name "Lestrade" appear in the passage below?

In [ ]:
passage = """During the first week or so we had no callers, and I had begun to think that my companion was as friendless a man as I was myself. Presently, however, I found that he had many acquaintances, and those in the most different classes of society. There was one little sallow rat-faced, dark-eyed fellow who was introduced to me as Mr. Lestrade, and who came three or four times in a single week. One morning a young girl called, fashionably dressed, and stayed for half an hour or more. The same afternoon brought a grey-headed, seedy visitor, looking like a Jew pedlar, who appeared to me to be much excited, and who was closely followed by a slip-shod elderly woman. On another occasion an old white-haired gentleman had an interview with my companion; and on another a railway porter in his velveteen uniform. When any of these nondescript individuals put in an appearance, Sherlock Holmes used to beg for the use of the sitting-room, and I would retire to my bed-room. He always apologized to me for putting me to this inconvenience. “I have to use this room as a place of business,” he said, “and these people are my clients.” Again I had an opportunity of asking him a point blank question, and again my delicacy prevented me from forcing another man to confide in me. I imagined at the time that he had some strong reason for not alluding to it, but he soon dispelled the idea by coming round to the subject of his own accord.
It was upon the 4th of March, as I have good reason to remember, that I rose somewhat earlier than usual, and found that Sherlock Holmes had not yet finished his breakfast. The landlady had become so accustomed to my late habits that my place had not been laid nor my coffee prepared. With the unreasonable petulance of mankind I rang the bell and gave a curt intimation that I was ready. Then I picked up a magazine from the table and attempted to while away the time with it, while my companion munched silently at his toast. One of the articles had a pencil mark at the heading, and I naturally began to run my eye through it.
Its somewhat ambitious title was “The Book of Life,” and it attempted to show how much an observant man might learn by an accurate and systematic examination of all that came in his way. It struck me as being a remarkable mixture of shrewdness and of absurdity. The reasoning was close and intense, but the deductions appeared to me to be far-fetched and exaggerated. The writer claimed by a momentary expression, a twitch of a muscle or a glance of an eye, to fathom a man’s inmost thoughts. Deceit, according to him, was an impossibility in the case of one trained to observation and analysis. His conclusions were as infallible as so many propositions of Euclid. So startling would his results appear to the uninitiated that until they learned the processes by which he had arrived at them they might well consider him as a necromancer.
“From a drop of water,” said the writer, “a logician could infer the possibility of an Atlantic or a Niagara without having seen or heard of one or the other. So all life is a great chain, the nature of which is known whenever we are shown a single link of it. Like all other arts, the Science of Deduction and Analysis is one which can only be acquired by long and patient study nor is life long enough to allow any mortal to attain the highest possible perfection in it. Before turning to those moral and mental aspects of the matter which present the greatest difficulties, let the enquirer begin by mastering more elementary problems. Let him, on meeting a fellow-mortal, learn at a glance to distinguish the history of the man, and the trade or profession to which he belongs. Puerile as such an exercise may seem, it sharpens the faculties of observation, and teaches one where to look and what to look for. By a man’s finger nails, by his coat-sleeve, by his boot, by his trouser knees, by the callosities of his forefinger and thumb, by his expression, by his shirt cuffs—by each of these things a man’s calling is plainly revealed. That all united should fail to enlighten the competent enquirer in any case is almost inconceivable.”
“What ineffable twaddle!” I cried, slapping the magazine down on the table, “I never read such rubbish in my life.”
“What is it?” asked Sherlock Holmes.
“Why, this article,” I said, pointing at it with my egg spoon as I sat down to my breakfast. “I see that you have read it since you have marked it. I don’t deny that it is smartly written. It irritates me though. It is evidently the theory of some arm-chair lounger who evolves all these neat little paradoxes in the seclusion of his own study. It is not practical. I should like to see him clapped down in a third class carriage on the Underground, and asked to give the trades of all his fellow-travellers. I would lay a thousand to one against him.”
“You would lose your money,” Sherlock Holmes remarked calmly. “As for the article I wrote it myself.”
“You!”
“Yes, I have a turn both for observation and for deduction. The theories which I have expressed there, and which appear to you to be so chimerical are really extremely practical—so practical that I depend upon them for my bread and cheese.”
“And how?” I asked involuntarily.
“Well, I have a trade of my own. I suppose I am the only one in the world. I’m a consulting detective, if you can understand what that is. Here in London we have lots of Government detectives and lots of private ones. When these fellows are at fault they come to me, and I manage to put them on the right scent. They lay all the evidence before me, and I am generally able, by the help of my knowledge of the history of crime, to set them straight. There is a strong family resemblance about misdeeds, and if you have all the details of a thousand at your finger ends, it is odd if you can’t unravel the thousand and first. Lestrade is a well-known detective. He got himself into a fog recently over a forgery case, and that was what brought him here.”
“And these other people?”
“They are mostly sent on by private inquiry agencies. They are all people who are in trouble about something, and want a little enlightening. I listen to their story, they listen to my comments, and then I pocket my fee.”
“But do you mean to say,” I said, “that without leaving your room you can unravel some knot which other men can make nothing of, although they have seen every detail for themselves?”
“Quite so. I have a kind of intuition that way. Now and again a case turns up which is a little more complex. Then I have to bustle about and see things with my own eyes. You see I have a lot of special knowledge which I apply to the problem, and which facilitates matters wonderfully. Those rules of deduction laid down in that article which aroused your scorn, are invaluable to me in practical work. Observation with me is second nature. You appeared to be surprised when I told you, on our first meeting, that you had come from Afghanistan.”
“You were told, no doubt.”
“Nothing of the sort. I knew you came from Afghanistan. From long habit the train of thoughts ran so swiftly through my mind, that I arrived at the conclusion without being conscious of intermediate steps. There were such steps, however. The train of reasoning ran, ‘Here is a gentleman of a medical type, but with the air of a military man. Clearly an army doctor, then. He has just come from the tropics, for his face is dark, and that is not the natural tint of his skin, for his wrists are fair. He has undergone hardship and sickness, as his haggard face says clearly. His left arm has been injured. He holds it in a stiff and unnatural manner. Where in the tropics could an English army doctor have seen much hardship and got his arm wounded? Clearly in Afghanistan.’ The whole train of thought did not occupy a second. I then remarked that you came from Afghanistan, and you were astonished.”
“It is simple enough as you explain it,” I said, smiling. “You remind me of Edgar Allen Poe’s Dupin. I had no idea that such individuals did exist outside of stories.”
Sherlock Holmes rose and lit his pipe. “No doubt you think that you are complimenting me in comparing me to Dupin,” he observed. “Now, in my opinion, Dupin was a very inferior fellow. That trick of his of breaking in on his friends’ thoughts with an apropos remark after a quarter of an hour’s silence is really very showy and superficial. He had some analytical genius, no doubt; but he was by no means such a phenomenon as Poe appeared to imagine.”
“Have you read Gaboriau’s works?” I asked. “Does Lecoq come up to your idea of a detective?”
Sherlock Holmes sniffed sardonically. “Lecoq was a miserable bungler,” he said, in an angry voice; “he had only one thing to recommend him, and that was his energy. That book made me positively ill. The question was how to identify an unknown prisoner. I could have done it in twenty-four hours. Lecoq took six months or so. It might be made a text-book for detectives to teach them what to avoid.”
I felt rather indignant at having two characters whom I had admired treated in this cavalier style. I walked over to the window, and stood looking out into the busy street. “This fellow may be very clever,” I said to myself, “but he is certainly very conceited.”
“There are no crimes and no criminals in these days,” he said, querulously. “What is the use of having brains in our profession. I know well that I have it in me to make my name famous. No man lives or has ever lived who has brought the same amount of study and of natural talent to the detection of crime which I have done. And what is the result? There is no crime to detect, or, at most, some bungling villainy with a motive so transparent that even a Scotland Yard official can see through it.”
I was still annoyed at his bumptious style of conversation. I thought it best to change the topic.
“I wonder what that fellow is looking for?” I asked, pointing to a stalwart, plainly-dressed individual who was walking slowly down the other side of the street, looking anxiously at the numbers. He had a large blue envelope in his hand, and was evidently the bearer of a message.
“You mean the retired sergeant of Marines,” said Sherlock Holmes.
“Brag and bounce!” thought I to myself. “He knows that I cannot verify his guess.”
The thought had hardly passed through my mind when the man whom we were watching caught sight of the number on our door, and ran rapidly across the roadway. We heard a loud knock, a deep voice below, and heavy steps ascending the stair.
“For Mr. Sherlock Holmes,” he said, stepping into the room and handing my friend the letter.
Here was an opportunity of taking the conceit out of him. He little thought of this when he made that random shot. “May I ask, my lad,” I said, in the blandest voice, “what your trade may be?”
“Commissionaire, sir,” he said, gruffly. “Uniform away for repairs.”
“And you were?” I asked, with a slightly malicious glance at my companion.
“A sergeant, sir, Royal Marine Light Infantry, sir. No answer? Right, sir.”
He clicked his heels together, raised his hand in a salute, and was gone."""

In [ ]:
# Count Sherlock

In [ ]:
# Count Lestrade

Solution for Email Splitting Problem


In [ ]:
mail1 = "gavin@hooley.com".split("@")
mail1
mail1[0]

In [ ]:
Username = mail1[0]
Domain = mail1[1]

print("Username:",Username, "\nDomain:",Domain)

In [ ]:
# Solution for Sherlock and Lestrade

print("Number of times 'Sherlock' appears in passage:", passage.count("Sherlock"))
print("Number of times 'Lestrade' appears in passage:", passage.count("Lestrade"))