E&C ENGR 216/217
Engineering Computation
Python Programming
Lecture 5
Muhammad Talha
Graduate Teaching Assistant
Electrical and Computer Engineering Department
1
Review Lec: 4
• Boolean Operators
• Compound Expressions
• Precedence & Associativity
• Assignment
• Conditional Statement with (break and Continue)
• Loops (while and For loops with else)
• Nesting.
String
Working with Strings:
What is String?
1. Any sequence of printable characters is referred to as a string which
doesn’t necessarily require any underlying meaning like a word.
2. Constructed either by using the string constructor str() or by
encompassing a group of characters in either two single quotes (') or two
double quotes ('')
Examples: 'a', "brb", 'What is your name?'.
Only requirement: quotes on either end of the string match.
'bad string“ is not a string in Python. It will show SyntaxError.
3
Sequence of characters
• We've talked about strings being a sequence of characters.
• A string is indicated between ' ' or " "
• The exact sequence of characters is maintained
Strings
Can use single or double quotes:
• S = "spam"
• s = 'spam'
Just don't mix them
• my_str = 'hi mom" ERROR
Inserting an apostrophe:
• A = "knight's" # mix up the quotes
• B = 'knight\'s' # escape single quote
String Representation
• Every character is "mapped" (associated) with a binary value which is
represented as integer for ease.
• UTF-8, subset of Unicode, is such a mapping
• The function ord() takes a character and returns its UTF-8 integer
value, chr() takes an integer and returns the UTF-8 character.
7
UTF-8
The Triple-Quote String
• Preserves all the format information of the string.
• If string spans multiple lines, those carriage returns between lines are
preserved.
• Allows you to type tables, paragraphs, whatever and preserve the formatting.
• If there are quotes, tabs or any information at all, it is preserved.
Example:
"""What’s up students!
I’m Dewan from UMKC.
Keep watching these lectures.
And, you will be the master of “Python Programming”
very soon."""
9
Non-Printing Characters
Some characters perform necessary operations but show up as
whitespace in the output. The two most common examples are:
1. carriage return \r
2. New line \n
3. tab \t
10
The Index
• Because the elements of a string are a sequence, we can associate
each element with an index, a location in the sequence:
• positive values count up from the left, beginning with index 0
• negative values count down from the right, starting with -1
Strings as a Sequence
• String objects are defined as a sequence of characters
• 'Hello World' is a sequence of 11 characters
• We can number the characters by their position in the sequence since
a sequence has an order
FIGURE: The index values for the string 'Hello World'.
12
Accessing an element
A particular element of the string is accessed by the index of the
element surrounded by square brackets [ ]
hello_str = 'Hello World'
print(hello_str[0]) => prints H
print(hello_str[-1]) => prints d
print(hello_str[11]) => ERROR
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.
More Indexing and Slicing
FIGURE: Indexing subsequences with slicing.
15
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
More Indexing and Slicing
FIGURE: Two default slice examples.
17
More Indexing and Slicing
FIGURE: Negative Indices.
FIGURE: Another slice example.
18
Extended Slicing
• Also takes three arguments:
• [start:finish:step]
• Defaults are:
• start is beginning, finish is end, step is 1
my_str = 'hello world'
my_str[0:11:2] 'hlowrd’
• Every other letter
Extended Slicing
FIGURE 4.6 Slicing with a step.
20
Copy Slice
A common slicing application is the copy slice. If the programmer
provides neither a beginning nor an end—that is, there is only a colon
character in the square brackets([:])—a complete copy of the string is
made. The [:] slice takes both defaults, from the beginning through the
end of the string.
Remember, a new string is yielded as the result of a slice; the original
string is not modified. Thus a copy slice is indeed a new copy of the
original string.
21
Some Python Idioms
• Idioms are python “phrases” that are used for a common task
that might be less obvious to non-python folk.
• 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]
String Operations
Strings are Iterable
• The individual elements of a string can be iterated using a for loop.
• Because strings are also a sequence, a string is iterated in the order in
which they appear in the string.`
24
Sequences are Iterable
The for loop iterates through each element of a sequence in order. For a
string, this means character by character:
String Operations
Concatenation (+)
• The operator + adds two string objects and creates a new string object
combining them together
Repetition (*)
• The * takes a string object and an integer and creates a new string
object
• The new string object has as many copies of the string indicated by the
integer
26
Basic String Operations
s = 'spam'
• length operator len()
len(s) 4
• + is concatenate
new_str = 'spam' + '-' + 'spam-'
print(new_str) spam-spam-
• * is repeat, the number is how many times
new_str * 3
'spam-spam-spam-spam-spam-spam-'
Some Details
• 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 two
strings, for repetition a string and an integer
What does a + b 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
The type()function
• You can check the type of the value associated with a variable using
type
my_str = 'hello world'
type(my_str) <type 'str'>
my_str = 245
type(my_str) <type 'int'>
Comparison Operators
Comparing Strings with One Character
Comparing Strings with More than One Character
31
String Comparisons, 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
Comparisons within sequence
• Compare based on the Unicode value
• 'a' < 'b' → True
• 'A' < 'B' → True
• '1' > '9' → False
• 'a' > 'A' → True
• 'a' < '0' → False
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 two characters are the
relationship between the string
• if one ends up being shorter (but equal), the shorter is smaller
• 'Alcfg'<'Alcgg’ : True
• 'Alcfg'<'Alcg’ : True
• 'Alcfg'<'Alcf’ : False
The in Operator
Useful for checking membership in a collection.
Example:
'a' in 'abcd'. The return value is True
• Takes two arguments: the collection we are testing and the
element we are looking for in the collection
• As a membership check, it returns a Boolean value to indicate
whether the first argument can be found in the second argument
35
Membership operations
• Can check to see if a substring exists in the string, the in
operator. Returns True or False
my_str = 'aabbccdd'
'a' in my_str True
'abb' in my_str True
'x' in my_str False
String Collections Are Immutable
Since a string is a collection—a sequence, in fact—it is tempting to try following kind of operations:
1. Create a string
2. Try to change a particular character in that string to a new character
However, this is not possible, because:
1. The string type is immutable
2. Once the object is created, its contents cannot be modified by assignment
37
Strings are immutable
• Strings are immutable, that is you cannot change one
once you make it:
• a_str = 'spam'
• a_str[1] = 'l' → ERROR
• However, you can use it to make another string (copy
it, slice it, etc.)
• new_str = a_str[:1] + 'l' + a_str[2:]
• a_str → 'spam'
• new_str →'slam'