Strings
A string is a sequence of characters surrounded by quotes; either single or double.
'I am a string!'
The only requirement is that the string must start and end with the same kind of quote.
"I prefer double quotes!"
This allows you to include quotes inside of quotes as a character in the string.
"I'm happy I started with a double quote!"
Using the interpreter, notice how the color of the input changes before and after you put quotes on both sides of the string. What happens when you do not include any quotes:
print(Hello)
Without the quotes, Python reads Hello as a variable that is undefined:
NameError: name 'Hello' is not defined
As we saw above, Python will not print an undefined variable, which is why we get the name error.
Quiz 1.7
Which of the following are valid strings in Python?
- A)
"Ada"
- B)
'Ada"
- C)
"Ada
- D)
Ada
- E)
'"Ada'
Answer
- A)
"Ada"
- E)
'"Ada'
Quiz 1.8
Define a variable, name
, and assign to it a string that is your name.
Answer
name = "Muhammad Ateeq"
String Operators
We can use the plus operator (+
) on strings, but it has a different meaning from when it is used on numbers. With string, plus means concatenation.
<string> + <string> outputs the concatenation of the two strings
Try concatenating the string 'Hello'
to name. You can create a space between the strings by adding a space to one of the strings. You can also continue to add strings as many times as you need.
name = 'Asif'
print('Hello ' + name + '!' + '!' + '!') # Output: Hello Asif!!!
However, you cannot use the plus operator to combine strings and integers, as in the case of:
print('My name is ' + 9)
you should see an error message like this:
TypeError: cannot concatenate 'str' and 'int' objects.
It is a bit surprising that you can multiply strings and integers!
print('!' * 12) # Output: !!!!!!!!!!!!
Above snippet multiplies the string by the integer to return 12 exclamation points!
Indexing
When you want to select sub-sequences from a string, it is called indexing. Use the square brackets []
to specify which part of the string you want to select.
<string>[<expression>]
For example, if we have the string 'bscsmorning' and we want to select the character in the zero position (that is, the first character), we would write:
'dsquare'[0] # -> 'd'
'dsquare'[2] # -> 'q'
The positions in a string are numbered starting with 0
, so this evaluates to 'd'. Indexing strings is the most useful when the string is given using a variable:
name = 'dsquare'
name[0] # -> 'd'
name[2] # -> 'q'
When you use negative numbers in the index it starts counting from the back of the string:
name = 'Asif'
name[-1] # -> f
name[-2] # -> i
When you try to index a character in a position where there is none, Python produces an error indicating that the index is out of range:
name = 'Asif'
name[4]
Will result into
IndexError: string index out of range
Quiz 1.9
Given the variable,
s = '<any string>'
Which of these pairs are two things with the exact same value?
- A)
s[3]
,s[1 + 1 + 1]
- B)
s[0]
,(s + s)[0]
- C)
s[0] + s[1]
,s[0 + 1]
- D)
s[1]
,(s + 'ity')[1]
- E)
s[-1]
,(s + s)[-1]
Answer
- A)
s[3]
,s[1 + 1 + 1]
- B)
s[0]
,(s + s)[0]
- E)
s[-1]
,(s + s)[-1]
Selecting Sub-Sequences from String (Slicing)
You can select a sub-sequence of a string by designating a starting position and an end position. Python reads the characters positions starting at 0, so that if we consider the string 'training'
that has 8 characters, there are 7 positions with 't'
being in the 0 position.
<string>[<expression>] --> a one-character string
<string>[<start expression>:<stop expression>] --> a string that is a
sub-sequence of the characters in the string, from the start position
up to the character before the stop position. If the start expression
is missing, the sub-sequence starts from the beginning of the string;
if the stop expression is missing, the sub-sequence goes to the end of
the string.
Examples:
word = 'assume'
word[3] # -> u
word[4:6] # -> me
word[4:] # -> me
word[:2] # as
word[:] # assume
Quiz 1.10
Write Python code that prints out dsquare (with a capital D), given the definition
s = 'dsquare'
Answer
s = 'dsquare'
print('D' + s[1:])
Quiz 1.11
For any string s
, Which of these is always equivalent to s
:
- A)
s[:]
- B)
s + s[0:-1 + 1]
- C)
s[0:]
- D)
s[:-1]
- E)
s[:3] + s[3:]
Answer
- A)
s[:]
- B)
s + s[0:-1 + 1]
- C)
s[0:]
- E)
s[:3] + s[3:]
Finding Strings in Strings
The find method is a built in operation, or method, provided by Python, that operates on strings. The output of find is the position of the string where the specified sub-string is found.
<search string>.find(<target string>)
If the target string is not found anywhere in the search string , then the output will be - 1. Here are some examples (try them yourself in the interpreter):
>>> pythagoras = 'There is geometry in the humming of the strings, there is music in the spacing of the spheres.'
>>> pythagoras.find('string')
40
>>> pythagoras[40:]
'strings, there is music in the spacing of the spheres.'
>>> pythagoras.find('T')
0
>>> pythagoras.find('sphere')
86
>>> pythagoras[86:]
'spheres'
>>> pythagoras.find('algebra')
-1
Quiz 1.12
Which of the following evaluate to -1
:
- A)
'test'.find('t')
- B)
"test".find('st')
- C)
"Test".find('te')
- D)
'west'.find('test')
Answer
- C)
"Test".find('te')
- D)
'west'.find('test')
Quiz 1.13
For any string s
, which of the following always has the value 0
?
- A)
s.find(s)
- B)
s.find('s')
- C)
's'.find('s')
- D)
s.find('')
- E)
s.find(s + '!!!') + 1
Answer
- A)
s.find(s)
- C)
's'.find('s')
- D)
s.find('')
- E)
s.find(s + '!!!') + 1
Using find with Numbers
In addition to passing in a target string to find, we can also pass in a number:
<search string>.find(<arget string>, <number>)
The number input is the position in the search string where find will start looking for the target string. So, the output is a number giving the position of the first occurrence of the target string in the search string at or after the number input position. If there is no occurrence at or after that position, the output is - 1. For example:
>>> motto = "I will learn the ART of Programming. Yes, I will!"
>>> motto.find('will'))
2
>>> motto.find('will', 0)
>>> 2
>>> motto.find('will', 2)
2
>>> motto.find('will', 3)
44
>>> motto.find('can', 44)
44
>>> motto.find('can', 45)
-1
Quiz 1.14
For any variables s and t that are strings, and i that is a number:
s = '<any string>'
t = '<any string>'
i = <any number>
which of these are equivalent to s.find(t, i)
:
- A)
s[i: ].find(t)
- B)
s.find(t)[ :i]
- C)
s[i: ].find(t) + i
- D)
s[i: ].find(t[i: ])
Answer
None of these