8 - Data Structures (Strings) - ST

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 54

Click icon to add picture

DATA STRUCTURES -8
(STRINGS)
Basimah Aljhne
Click icon to add picture
1. The string Type
2. String Operations
3. String methods and functions
4. Example
THE STRING TYPE Click icon to add picture

1. What is String in Python?


2. Non-printing characters
3. How to access characters in a string?
4. How to change or delete a string?
What is String in Python?

 A string is a sequence of characters.


 A character is simply a symbol. For example, the English language has 26 characters.
 Computers do not deal with characters, they deal with numbers (binary).
 Even though you may see characters on your screen, internally it is stored and
manipulated as a combination of 0's and 1's.
 This conversion of character to a number is called encoding, and the reverse process
is decoding.
 ASCII and Unicode are some of the popular encoding used.
 In Python, string is a sequence of Unicode character.
 Every character is "mapped" (associated) with an integer
 UTF-8, subset of Unicode, is such a mapping

 the function ord()

------------------------------------------------------------------
------------------------------------------------------------------
 The function chr()

------------------------------------------------------------------
------------------------------------------------------------------
Question from 1 to 4
How to create a string in Python?
 There are two ways to declare a  f you want to write string on
string written on a line by using multiple lines using a pair of 3
single quotes or double quotes. single quotes.

 Just don't mix them!

str1= 'hi mom" 

SyntaxError: EOL while scanning string literal


How to create a string in Python?
 Using constructor str ()

 Using constructor str () to convert different data type to string.


How to create a string in Python?`

using single quotes

Using constructor str ()


using double quotes

using using a pair of


3 single quotes.
Non-printing characters (Escape Characters)
 Escape characters are special characters in Python.
 It is non-printable characters
Question from 5 to 6
How to access characters in a string?
 We can access individual characters using indexing and a range of characters using
slicing.
 Index starts from 0.
 Python allows negative indexing for its
sequences.
 The index of -1 refers to the last item, -2
to the second last item and so on
hello_str = 'Hello World'
 A particular element of the string is
accessed by the index of the element Accessing an element:
surrounded by square brackets [ ] print(hello_str[1]) => e
 Trying to access a character out of index print(hello_str[-1]) => d
print(hello_str[11]) =>
range will raise an IndexError. The index
indexError: string index out of range
must be an integer.
print(hello_str[1.3]) =>
 We can't use float or other types, this
will result into TypeError. TypeError: string indices must be integers
Print the string: Print the Last Character:

Print the First Character:


How to access characters in a string? Using index

Index syntax?

Sring_var [ ]

Positive number Negative number

• If you want to • If you want to access


access the string the string from rear
from front • Strat from -1
• Strat from 0
How to access characters in a string?
Slicing, the rules:
 slicing is the ability to select a subsequence of the overall sequence
 uses the syntax [start : finish], where:
start is the index of where we start the
subsequence
finish is the index of one after where we end the subsequence

>> hello_string="Hello World"


>>> hello_string[6:10]
>>> ‘Worl’
How to access characters in a string?
Slicing, the rules:
 slicing is the ability to select a subsequence of the overall sequence
 uses the syntax [start : finish], where:
start is the index of where we start the
subsequence
finish is the index of one after where we end the subsequence
 if either start or finish are not provided, it defaults to the beginning of the sequence
for start and the end of the sequence for finish
half open range for slices:
 slicing uses what is called a half-open range
 the first index is included in the sequence
 the last index is one after what is included
>> hello_string="Hello World"
>>> hello_string[6:10]
>>> ‘Worl’

>>> hello_string[6:]
>>> ‘Wold’

>>> hello_string[:5]
>>> ‘Hello’
Slicing _ Negative indices

>>> hello_string[-1]
>>> ‘d’

>>> hello_string[3:-2]
>>> ‘lo wor’
Extended Slicing

takes three arguments:


[start:finish: steps]

defaults are:
start is beginning, finish is end, steps is 1

my_str = 'hello world'


my_str[0:11:2]  'hlowrd'

>>> hello_string[ : : 2]
Copy Slice
How to make a copy of a string:
my_str = 'hi mom'

new_str = my_str[:]

How to reverse a string

my_str = "madam I'm adam"

reverseStr = my_str[::-1]
How to access characters in a string? Using index
Using Slicing
Slicing syntax?

Sring_var [ : : ]

Start index

Finish index

steps
How to change or delete a string?

 Strings are immutable.


 This means that elements of a string cannot be changed once it has been assigned.
We can simply reassign different strings to the same name.

 We cannot delete or remove characters from a string.


 But deleting the string entirely is possible using the keyword del.
String=‘Hi’ String

Value

H i Attribute Operation Methods Function

Indexing

slicing

Immutable
What happens when you invoke each of these commands‫؟‬
greet[1]
greet[1:8]
greet = "Have a great day"
greet[8: ]
greet[-5]
Greet[-7:-3]

This mean we can write a


variable as index however
variable value has to be integer

Write a program called reverseString.py which tak


es
String of text entered by the user and prints out
takes String of text entered by the user

prints out the exact same string but in reverse :


• Can I use Slicing ?
• Can I use using indexing ?
• There is method can do this? Var[ : : -1]
• There is function can do this?
• Iterating Through String
Click icon to add picture
STRING OPERATIONS
1. Concatenation (+) and Repetition (*)
2. Comparison Operators
3. Iterating Through String
Concatenation (+) and Repetition (*)

 The + operator does this in Python. Simply writing two string literals together also
concatenates them.
 The * operator can be used to repeat the string for a given number of times.
Concatenation (+) and Repetition (*)

 There are many operations that can be performed with string which makes it one of
the most used datatypes in Python.

 both + and * on strings makes a new string, does not modify the arguments.

 order of operation is important for concatenation, irrelevant for repetition

 The types required are specific.


 For concatenation you need at least two strings, for repetition a string and an integer
 what does + mean?
 what operation does the above represent? It depends on the types!
two strings, concatenation
two integers addition
 the operator + is overloaded
The operation + performs depends on the types it is working on
Comparison Operators
single char:
 Python 3 uses the Unicode mapping for characters.
 Allows for representing non-English characters
 UTF-8, subset of Unicode, takes the English letters, numbers and punctuation marks
and maps them to an integer
 Single character comparisons are based on that number
It makes sense to compare within a sequence (lower case, upper case, digits).
'a' < 'b'  True
'A' < 'B'  True
'1' < '9'  True

'a' < 'A'  False


'a' < '0'  False
Comparison Operators

Whole strings:
 Compare the first element of each string
if they are equal, move on to the next character in each

 if they are not equal, the relationship between those to characters are the
relationship between the string
if one ends up being shorter (but equal), the shorter is smaller

Examples:
'aaab' < ‘aaac'  True
‘aa' < ‘aaz'  True

The first string is the same but shorter.


Thus it is smaller.
Iterating Through String

 Using for loop we can iterate through a string.

String Membership Test


 We can test if a sub string exists within a string or not, using the keyword in.

my_str = 'aabbccdd'

'a' in my_str  True


‘abb' in my_str  True
‘x' in my_str  False
String=‘Hi’ String

Value

H i Attribute Operation Methods Function


Indexing Concatenation (+)

Repetition (*)
slicing
Comparison Operators
Immutable Iterating Through String

String Membership Test


Question from 7 to 8
Write
•What is athe
program that
output of theask user tocode?
following enter a string
• Print the number of letters in given string

1)counter
2)Tool that iterate
through string
STRING METHODS AND Click icon to add picture

FUNCTIONS
1. String Method vs Function
2. Python String Methods
3. Built-in functions to Work with Python
String Method vs Function
function method
 is a program that performs some  a method is a variation on a function
operation. Its details are hidden  like a function, it has input arguments
(encapsulated), only it's interface and an output
provided.  Unlike a function, it is applied in the
 A function takes some number of inputs context of a particular object
(arguments) and returns a value based  This is indicated by the dot notation
on the arguments and the function's invocation
operation. Example:
Example: upper is the name of a method. It
generates a new string that has all upper
The len function takes as an argument a case characters of the string it was called
string and returns an integer, the length of with.
a string
my_str = 'Python Rules!'
my_str = 'Hello World’
my_str.upper()'PYTHON RULES!'
len(my_str)  11 # space counts
Python String Methods

More dot notation


 in general, dot notation looks like: object.method(…)
 It means that the object in front of the dot is calling a method that is associated
with that object's type
 The method's that can be called are tied to the type of the object calling it.
 Each type has different methods

Chaining methods
 Methods can be chained my_str = 'Python Rules!’
together. my_str.upper()  'PYTHON RULES!'
 Perform first operation, yielding an my_str.upper().find('O')  4
object
 Use the yielded object for the next
method
)( Find
my_str = 'hello'
my_str.find('l') # find index of 'l' in my_str
 2
• Note how the method 'find' operates on the string object my_str and the two are
associated by using the “dot” notation: my_str.find('l').
• Terminology: the thing(s) in parenthesis, i.e. the 'l' in this case, is called an
argument
Python String Methods

Optional Arguments
• Some methods have optional arguments: a_str = 'He had the bat'
• if the user doesn't provide one of these, a_str.find('t’)  7
a default is assumed # 1st 't',start at 0
a_str.find('t',8)  13
• For example: find has a default second
# 2nd 't'
argument of 0, where the search begins
)( split

 The split method will take a string and break it into multiple new string parts
depending on the argument character.
 by default, if no argument is provided, split is on any whitespace character
(tab, blank, etc.)

 you can assign the pieces with multiple assignment if you know how many pieces
are yielded
lower( )
This method returns a copy of the string in which all case-based characters have been lowercased.

replace()
Following is the syntax for replace() method str.replace(old, new[, max])
Parameters:
old − This is old substring to be replaced.
new − This is new substring, which would replace old substring.
max − If this optional argument max is given, only the first count occurrences are replaced.

str = "this is string example....wow!!! this is really string"


print( str.replace("is", "was”)
print( str.replace("is", "was“,3))
Determining Method Name and Method Arguments

• You can use IDLE to find available methods for any type.
• You enter a variable of the type, followed by the '.' (dot) and then a tab
• Remember, methods match with a type. Different types have different methods
• If you type a method name, IDLE will remind you of the needed and optional
arguments.
Your Turn complete
it
Built-in functions to Work with Python

• Various built-in functions that work with sequence, works with string as well
• Some of the commonly used ones is len().
• len() returns the length (number of characters) of the string.
What doing Function
takes a character and returns its UTF-8 integer ord(‘a’)
value
takes an integer and returns the UTF-8 chr(97)
.character
takes an object and return the number of its len(object)
items
Return the index of an element and the element enumerate(iterable, start=0)
itself

Your Turn complete


it
String=‘Hi’ String

Value

H i Attribute Operation Methods Function


Indexing Concatenation (+) String. Find() len(string)

slicing Repetition (*) String. split () chr(string)

Immutable Comparison Operators String. lower( )


Iterating Through
String. replace()
String
String Membership
Test
Question from 9 to 10
1-converts the first character of a string to capital
(uppercase) letter.

2-find if the string has non-alphabets.


Click icon to add picture
EXAMPLE
Important to do at home :
read chapter 4

+ execute the following from your book:

Code Listing 4.4 p212


1. What is String in Python?
1. What is String in Python?
1. What is String in Python?
Given the string " Monty Python ":
(a) Write an expression to print the first character.
(b) Write an expression to print the last character.
(c) Write an expression including len to print the last character.
(d) Write an expression that prints "Monty".
2. String Operations

What will be printed by the following?


x=' This is a test. ‘
print (x * 3)

You might also like