Topic 8
Topic 8
Python Programming
CT108-3-1-PYP
TOPIC LEARNING OUTCOMES
This tells the interpreter, this is an apostrophe, not an opening quote to another string, so ignore it.
>>> x = int(apple) – 10
>>> print(x) Raw input numbers must be
90
converted from strings
abc = a b c
Index: 0 1 2
-3 -2 -1
• Expression retrieving a character at specified index:
<str-expr> [ <index-expr> ]
"abc"[0] a "abc"[2] c
"abc"[1] b len("abc") 3
If we try to access index out of the range or use decimal number, we will get
errors. So be careful when constructing index values and slices
By default, print() separates multiple outputs with spaces
You can change this to any string that you want, for example, a colon and a space (': ')
>>> print(1, 2, 3, sep=': ')
1: 2: 3
By default, print() ends its output with a newline ('\n')
>>> for i in range(3):
print(i) Passing the whitespace to the end parameter
0 (end=' ') indicates that the end character must be
1 identified by whitespace and not a newline.
2
You can change this, for example, to a hyphen
>>>for i in range(3):
print(i, end='-')
0-1-2-
The in keyword can also be used to check to see if one string is "in" another
string
fruit = 'banana'
The in expression is a logical expression print('n' in fruit)
print('m' in fruit)
and returns True or False and can be print('nan' in fruit)
print(len("GATTACA")) ← Length
print("A" * 10)
← Repeat
print("GAT" in "GATTACA")
← Substring test
print("AGT" in "GATTACA")
b a n a n a
0 1 2 3 4 5
A
0 A
l
1 l
i
2 i
c
3 c
e
4 e
b
a
The iteration variable is completely taken care of by the for loop n
a
n
index = 0
fruit = 'banana'
for letter in fruit :
while index < len(fruit) :
letter = fruit[index]
a
print letter
print letter index = index + 1
It is often useful to take part of a string or analyse it or use it is another part of the code.
Example:
You have been asked to write a program to check if a string contains a One of the checks will mean that you need to slice the string taking all the
valid address. characters from the left-hand part of the string up to character
Forward 0 1 2 3 4 5 6 7 8
index
M i n e c r a f t
-9 -8 -7 -6 -5 -4 -3 -2 -1 Reverse
index
Example:
0 1 2 3 4 5 6 7 8
When SLICING, think of
the index as pointing to M i n e c r a f t
the character to the left
of the arrow -9 -8 -7 -6 -5 -4 -3 -2 -1
0 1 2 3 4 5 6 7 8
M i n e c r a f t
-9 -8 -7 -6 -5 -4 -3 -2 -1
• First Character M
firstChar = myString[0]
• Last Character
t
lastChar = myString[-1]
These functions
These functions
are already built
Python has several do not modify the
into every string -
string functions original string,
we invoke them
which are in the instead they return
by appending the
string library a new string that
function to the
has been altered
string variable
<expr> .method()
"abc abc".count("b") 2
The string format() method allows you detailed control over what is printed and its
arrangement (including alignment; width; your choice of date, time and number formats; and
many other things).
Here is an example of how s.format() can be used to control what is printed:
>>> print('{} is {}'.format('Big Bird', 'yellow'))
Big Bird is yellow
>>> print('{} is {}'.format('Oscar', 'grumpy'))
Oscar is grumpy
>>> s = "GATTACA"
>>> s[3] = "C"
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment
>>> s = s[:3] + "C" + s[4:]
>>> s
'GATCACA'
>>> s = s.replace("G","U")
>>> s
'UATCACA'
String methods do not modify the string; they return a new string.
sequence = "ACGT"
print(sequence.replace("A", "G"))
print(sequence)
Or
sequence = "ACGT"
new_sequence = sequence.replace("A", "G")
print(new_sequence)
•
When a string method returns a string, it is a different object; the original string is not
changed
aStr = 'my cat is catatonic'
newStr = aStr.replace('cat', 'dog')
print(newStr)
print(aStr)
•However, you can associate the old string name with the new object
aStr = 'my cat is catatonic'
aStr = aStr.replace('cat', 'dog')
print(aStr)
Returns a space-padded string with the original string centered to a total of width
columns
3 count(str, beg= 0,end=len(string))
Counts how many times str occurs in string, or in a substring of string if starting
index beg and ending index end are given
3 decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for encoding. encoding defaults to the
default string encoding.
4 encode(encoding='UTF-8',errors='strict')
Determines if string or a substring of string (if starting index beg and ending index
end are given) ends with suffix; Returns true if so, and false otherwise
6 expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not
provided
CT108-3-1-PYP Strings SLIDE 33
find(str, beg=0 end=len(string))
7
Determine if str occurs in string, or in a substring of string if starting index beg and
ending index end are given; returns index if found and -1 otherwise
8 index(str, beg=0, end=len(string))
9 isa1num()
Returns true if string has at least 1 character and all characters are alphanumeric
and false otherwise
10 isalpha()
Returns true if string has at least 1 character and all characters are alphabetic and
false otherwise
11 isdigit()
12 islower()
Returns true if string has at least 1 cased character and all cased characters are in
lowercase and false otherwise
13 isnumeric()
Returns true if a unicode string contains only numeric characters and false otherwise
14 isspace()
Returns true if string contains only whitespace characters and false otherwise
CT108-3-1-PYP Strings SLIDE 34
15 istitle()
Returns true if string has at least one cased character and all cased characters are in
uppercase and false otherwise
17 join(seq)
Returns a space-padded string with the original string left-justified to a total of width
columns
20 lower()
Replaces all occurrences of old in string with new, or at most max occurrences if max
given
26 rfind(str, beg=0,end=len(string))
28 rjust(width,[, fillchar])
30 split(str="", num=string.count(str))
Splits string according to delimiter str (space if not provided) and returns list of
substrings; split into at most num substrings if given
31 splitlines( num=string.count('\n'))
Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs
removed
CT108-3-1-PYP Strings SLIDE 36
32 startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting index beg and ending index
end are given) starts with substring str; Returns true if so, and false otherwise
33 strip([chars])
34 swapcase()
35 title()
Returns "titlecased" version of string, that is, all words begin with uppercase, and the
rest are lowercase
36 translate(table, deletechars="")
Translates string according to translation table str(256 chars), removing those in the
del string
37 upper()
38 zfill (width)
Returns original string leftpadded with zeros to a total of width characters; intended
for numbers, zfill() retains any sign given (less one zero)
39 isdecimal()
Returns true if a unicode string contains only decimal characters and false otherwise
• String type
• Read/Convert
• Indexing strings []
• Slicing strings [2:4]
• Looping through strings with for and while
• Concatenating strings with +
• String operations