0% found this document useful (0 votes)
15 views40 pages

Topic 8

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views40 pages

Topic 8

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Topic 8 – Strings

Python Programming
CT108-3-1-PYP
TOPIC LEARNING OUTCOMES

At the end of this topic, you should be able to:


– Understand what is strings
– Understand how to search, find and loop through string

CT108-3-1-PYP Strings SLIDE 2


Contents & Structure

Defining string type of data

Searching through string

Finding element in a string

Looping through string/ list


CT108-3-1-PYP Strings SLIDE 3 ‹#›
Strings
A Python strings is a datatype be it a letter, number, punctuation or any other keyboard character

To initialize enclose the text with a single or double quote


stringTitle = “Minecraft” stringSubtitle = ‘Awesome Game’

To include a quote in the string use the backward slash


stringSubtitle = ‘It\’s an awesome game’

This tells the interpreter, this is an apostrophe, not an opening quote to another string, so ignore it.

In python, strings are treated as a special type of list

Python uses Unicode format to represent characters.

CT108-3-1-PYP Strings SLIDE 4 ‹#›


String Data Type -recap

>>> str1 = "Hello”


>>> str2 = 'there'
A string is a sequence of characters
>>> bob = str1 + str2
>>> print(bob)
Hellothere
A string literal uses quotes 'Hello' or
>>> str3 = '123' “Hello”
>>> str3 = str3 + 1
Traceback (most recent call last): File "<stdin>", line 1, in
<module>TypeError: cannot concatenate 'str' and 'int' objects For strings, + means “concatenate”
>>> x = int(str3) + 1
>>> print(x) When a string contains numbers, it is
124 still a string
>>>

We can convert numbers in a string


into a number using int()

CT108-3-1-PYP Strings SLIDE 5 ‹#›


Reading and Printing a string

print('Enter your name: ')


name = input(">")
print('Hi ' + name + ' Lets learn about strings in Python!')

CT108-3-1-PYP Strings SLIDE 6


‹#›
String Concatenation

Joining of two or more strings into one is called concatenation.

The + operator does this in Python.


a = 'Hello'
b = a + 'There'
print (b)
c = a + ' ' + 'There'
print (c)
The * operator can be used to repeat the string for a given number of times
word = 'hello'
print(word * 3)

CT108-3-1-PYP Strings SLIDE 7 ‹#›


Reading and Converting

>>> name = input('Enter:')


Enter:Chuck We prefer to read data in using
>>> print(name)
Chuck
strings and then parse and
convert the data as we need
>>> apple = input('Enter:')
Enter:100
>>> x = apple – 10 This gives us more control over
Traceback (most recent call last): File "<stdin>", line 1, in error situations and/or bad user
<module>TypeError: unsupported operand type(s) for -: 'str' and
'int’ input

>>> x = int(apple) – 10
>>> print(x) Raw input numbers must be
90
converted from strings

CT108-3-1-PYP Strings SLIDE 8


‹#›
Strings are sequences

A string is a sequence of characters.


• Each character in the string has an index.

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

CT108-3-1-PYP Strings SLIDE 9


Accessing Individual Characters

name = 'Aziah Binti Abdollah’


We can access individual characters of print('First character is '+name[0])

string using indexing. print('Last character is '+name[-1])


print('Fifth character is '+name[5])

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

The index value must be an integer and starts at zero

CT108-3-1-PYP Strings SLIDE 10 ‹#›


Special characters

• The backslash is used to introduce a special Escape Meaning


character. sequence
print("He said, "Wow!"")
\\ Backslash
File "<stdin>", line 1
"He said, "Wow!"" \’ Single quote
^
SyntaxError: invalid syntax \” Double
print("He said, 'Wow!'")
He said, 'Wow!’
quote
print("He said, \"Wow!\"") \n Newline
He said, "Wow!"
\t Tab

CT108-3-1-PYP Strings SLIDE 11


The print separator and end


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-

CT108-3-1-PYP Strings SLIDE 12


Using in as an Operator

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)

used in an if statement if 'a' in fruit :


print ('Found it!')

CT108-3-1-PYP Strings SLIDE 13


‹#›
More string functionality

print(len("GATTACA")) ← Length

print("GAT" + "TACA") ← Concatenation

print("A" * 10)
← Repeat
print("GAT" in "GATTACA")
← Substring test
print("AGT" in "GATTACA")

CT108-3-1-PYP Strings SLIDE 14


Strings Have Length

• There is a built-in function len that gives us the length of a string

b a n a n a
0 1 2 3 4 5

>>> fruit = 'banana'


>>> print len(fruit)
6

CT108-3-1-PYP Strings SLIDE 15


Iterating over strings

name = "Alice" name = "Alice"


for c in name: for i in range(len(name)):
print(c) print(str(i) +" "+ name[i])

A
0 A
l
1 l
i
2 i
c
3 c
e
4 e

CT108-3-1-PYP Strings SLIDE 16


Iterating over strings

A definite loop using a for statement is much more elegant

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

CT108-3-1-PYP Strings SLIDE 17


‹#›
Slicing Strings – What is it?

Slicing means taking part of a string as in cutting it up

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

CT108-3-1-PYP Strings SLIDE 18 ‹#›


Slicing Strings –How to do it?

Strings have indices just like lists:

• Forward index starts at 0 from the LHS


• Reverse index starts at -1 from the RHS

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

To specify a slice, you need to

• give the START position from the left-hand side


• give the END position from the left-hand side
• Separate the two values with a colon

Example:

• newString = myString [1:3]

CT108-3-1-PYP Strings SLIDE 19 ‹#›


Slicing Strings –Some Rules

• If did not specify a START it defaults to the beginning:


newString = myString[:3] This means start at
position 0 end at position 3

• If did not specify an END it defaults to the end:

newString = myString[3:] This means start at


position until the end

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

CT108-3-1-PYP Strings SLIDE 20


‹#›
Slicing Strings – Quickstart

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]

• All characters but the first


slice =myString[1:] inecraft
• All characters but the last
slice = myString[:-1] Minecraf

CT108-3-1-PYP Strings SLIDE 21


‹#›
Accessing substrings - Slicing

>>> myString = “GATTACA”


>>> myString[1:3]
‘AT’
>>> myString[:3]
‘GAT’
>>> myString[4:]
‘ACA’
>>> myString[3:5]
‘TA’
>>> myString[:]
‘GATTACA’

CT108-3-1-PYP Strings SLIDE 22


String Method

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

CT108-3-1-PYP Strings SLIDE 23


Strings are objects

• Objects have methods.

<expr> .method()

• Some string methods:


"abc abc".capitalize()  Abc abc

"abc abc".count("b")  2

"abc abc".islower()  True

• Strings are immutable.

CT108-3-1-PYP Strings SLIDE 24


Some more string methods

"AbC aBc".lower()  abc abc

"abc abc".replace("c ", "xx")  abxxabc

"abc abc".startswith("ab")  True

"AbC aBc".swapcase()  aBc AbC

"Abc abc".upper()  ABC ABC

CT108-3-1-PYP Strings SLIDE 25


The string format method


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

CT108-3-1-PYP Strings SLIDE 26


UPPER CASE VS LOWER CASE

>>> greet = 'Hello Bob'


>>> nnn = greet.upper()
>>> print(nnn)
HELLO BOB You can make a copy of a string in
>>> www = greet.lower() lower case or upper case
>>> print(www)
hello bob

Often when we are searching for a


string using find() - we first convert
the string to lower case so we can
search a string regardless of case

CT108-3-1-PYP Strings SLIDE 27


‹#›
Searching a String
• We use the find() function to search for a b a n a n a
substring within another string
• find() finds the first occurrence of the 0 1 2 3 4 5
substring
• If the substring is not found, find() returns -1
• Remember that string position starts at zero >>> fruit = 'banana'
>>> pos = fruit.find('na')
>>> print pos
2
>>> aa = fruit.find('z')
>>> print aa
-1

CT108-3-1-PYP Strings SLIDE 28


Strings are immutable

• Strings cannot be modified; instead, create a new one.

>>> 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'

CT108-3-1-PYP Strings SLIDE 29


Strings are immutable

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)

CT108-3-1-PYP Strings SLIDE 30


Strings are immutable


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)

CT108-3-1-PYP Strings SLIDE 31


Stripping Whitespace
>>> greet = ' Hello Bob '
Sometimes we want to take a >>> greet.lstrip()
string and remove whitespace at
'Hello Bob '
the beginning and/or end
>>> greet.rstrip()
' Hello Bob'
lstrip() and rstrip() to the left and >>> greet.strip()
right only 'Hello Bob'
>>>

strip() Removes both begin and


ending whitespace

CT108-3-1-PYP Strings SLIDE 32


‹#›
Built-in String Methods:
1 capitalize()

Capitalizes first letter of string


2 center(width, fillchar)

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')

Returns encoded string version of string; on error, default is to raise a ValueError


unless errors is given with 'ignore' or 'replace'.
5 endswith(suffix, beg=0, end=len(string))

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))

Same as find(), but raises an exception if str not found

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()

Returns true if string contains only digits and false otherwise

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 is properly "titlecased" and false otherwise


16 isupper()

Returns true if string has at least one cased character and all cased characters are in
uppercase and false otherwise
17 join(seq)

Merges (concatenates) the string representations of elements in sequence seq into a


string, with separator string
18 len(string)

Returns the length of the string


19 ljust(width[, fillchar])

Returns a space-padded string with the original string left-justified to a total of width
columns
20 lower()

Converts all uppercase letters in string to lowercase


21 lstrip()

Removes all leading whitespace in string


22 maketrans()

Returns a translation table to be used in translate function.


23 max(str)

Returns the max alphabetical characterStrings


from the string str
CT108-3-1-PYP SLIDE 35
24 min(str)

Returns the min alphabetical character from the string str

25 replace(old, new [, max])

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))

Same as find(), but search backwards in string

27 rindex( str, beg=0, end=len(string))

Same as index(), but search backwards in string

28 rjust(width,[, fillchar])

Returns a space-padded string with the original string right-justified to a total of


width columns.
29 rstrip()

Removes all trailing whitespace of string

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])

Performs both lstrip() and rstrip() on string

34 swapcase()

Inverts case for all letters in string

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()

Converts lowercase letters in string to uppercase

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

CT108-3-1-PYP Strings SLIDE 37


Summary / Recap of Main Points

• String type
• Read/Convert
• Indexing strings []
• Slicing strings [2:4]
• Looping through strings with for and while
• Concatenating strings with +
• String operations

CT108-3-1-PYP Strings SLIDE 38


What To Expect Next Week

In Class Preparation for Class


• List • Understand the use of List.
• What is the different between strings
and list.

CT108-3-1-PYP Strings SLIDE 39


CT108-3-1-PYP Strings SLIDE 40

You might also like