Lecture 13
Sequences-Part-1(Strings)
Fall 2021-BSCS (11-A)
Shah Khalid
Email: [Link]@[Link]
National University of Sciences and Technology
1 1
Today…
• Last Session:
• Loops
• Today’s Session:
• Sequences- Part I (Strings):
• Basic String Operations
• String Representation
• String Methods
• Announcement:
• Be ready for Next Quiz
Overview
• So far, we have seen how to define strings, get them as input, assign
them to variables, and print them out
• Unfortunately, this is not quite enough to do any serious text-based
computing!
• For this, we need some more string operations (which we know some
already) and functions
Indexing Strings
• Recall that a string is a sequence of characters, which can be thought
of as being stored in numbered buckets, starting from the left with 0
H E L L O
0 1 2 3 4
• Individual characters that make up the string can then be accessed
through the operation of indexing
>>> s = "HELLO"
>>> s[0]
'H'
>>>
Indexing Strings
• Notice that in a string of n characters, the last character is at position
n-1, because the indexes start at 0
H E L L O
0 1 2 3 4
>>> s = "HELLO"
>>> s[4] Accessing the bucket at position n (or more)
'O' will result in an IndexError
>>> s[5]
Traceback (most recent call last): File "<stdin>", line 1, in
<module> IndexError: string index out of range
>>>
Indexing Strings
• We can also index a string from the right end using a negative
number, after which Python will add the length of the string to the
number and index the string at the resultant number (or position)
-1 + 5 (i.e., the length
-5 -4 -3 -2 -1 of the string) = 4
H E L L O
0 1 2 3 4
>>> s = "HELLO"
>>> s[-1]
'O'
>>> s[-5]
'H'
>>>
Slicing Strings
• Aside from indexing, which returns a string containing a single
character from a larger string, it is also possible to access a
contiguous sequence of characters (or a substring) from a string
• In Python, this is accomplished through an operation called slicing,
which takes the form <string>[<start>:<end>]
• start and end should be int-valued expressions
• Slicing returns the substring starting at start and running up to, but
not including, end
Slicing Strings
• Examples:
H E L L O W O R L D
0 1 2 3 4 5 6 7 8 9 10
>>> greet = "HELLO WORLD"
>>> greet[0:5]
'HELLO' 0 is assumed as the default
>>> greet[6:11] if start is missing
'WORLD'
>>> greet[:5]
'HELLO'
Slicing Strings
• More examples:
H E L L O W O R L D
0 1 2 3 4 5 6 7 8 9 10
Last position is assumed as
>>> greet[6:]
the default if end is missing
'WORLD'
>>> greet[:]
'HELLO WORLD'
>>>
Concatenating and Repeating Strings
• The string data type also supports concatenation (+) and repetition
(*) operations for putting strings together
• Concatenation (which we’ve seen before) builds a string by ”gluing” two
strings together
• Repetition builds a string by multiple concatenations of a string with itself
>>> s1 = "Hello "
>>> s2 = "World "
>>> s3 = s1 + s2
>>> s3
'Hello World '
>>> s4 = s3 * 2
>>> s4
'Hello World Hello World '
>>>
Getting the Length and Iterating Over Strings
• Another useful function is len(), which tells how many characters are
in a string
• As seen before, we can also iterate over the characters of a string
shah = "Hello All"
count = 0
while count < len(shah):
print(shah[count], end = " ")
count = count + 1
Getting the Length and Iterating Over Strings
• Another useful function is len(), which tells how many characters are
in a string
• As seen before, we can also iterate over the characters of a string
#The program continues here…
print() This for loop is equivalent
to the earlier while loop
for i in shah:
print(i, end = " ")
Hello All
Output:
Hello All
Summary of the Basic String Operations
• The following table summarizes the basic string operations
Operator Meaning
+ Concatenation
* Repetition
<string>[] Indexing
<string>[ : ] Slicing
len(<string>) Length
for <var> in <string> Iteration through
characters
String Representation
• By now, you have started getting the hang of computing with textual
(string) data
• But, how does a computer manipulate strings?
• Earlier in class, we discussed that numbers are stored in binary notation (i.e.,
sequence of zeros and ones)
• Textual information is represented exactly the same way!
• In particular, each character is translated into a number, and the entire
string is stored as a sequence of (binary) numbers in computer memory
• What number is used to represent any given character?
String Representation
• It does not really matter what number is utilized to represent any
given character as long as all types of computers use the same number
• Consider a situation that would result if, say, a Windows-based and a
Linux-based computers each used its own numbers (or encoding)
• What happens if you type some strings in a text file using a Windows-based
machine and send that file to someone who has a Linux-based machine?
• The file at the Linux-based machine will have different strings than the
ones in the file at the Windows-based machine!
• How to avoid this problem?
String Representation
• Computer systems nowadays use industry standard encodings
• One important standard is called ASCII (American Standard Code for
Information Interchange)
• ASCII uses the numbers 0 through 127 to represent the characters
typically found on an (American) computer keyboard
• E.g., The capital letters A-Z are represented by the values 65-90, and the
lower-case a-z characters are represented by the values 97-122
String Representation
• ASCII is American-centric
• What about other languages?
• Unicode is a much larger standard that includes support for the characters of
nearly all written languages (ASCII is a subset of Unicode)
• Python uses Unicode and provides a couple of built-in functions that
allow us to switch back and forth between characters and their
corresponding Unicode numeric values
• The ord() function returns the numeric (“ordinal”) code of a single character
• The chr() function goes the other direction
String Representation
• Here are some interactive examples:
>>> ord("a") >>> ord("D")
97 68
>>> ord("b") >>> ord("Z")
98 90
>>> ord("z") >>> chr(90)
122 'Z'
>>> ord("A") >>> chr(65)
65 'A'
>>> >>>
Strings Are Immutable
• Strings are immutable (i.e., cannot be changed after they are created)
>>> mystr1 = "Python strings are immutable"
>>> mystr1[0] = "X"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
id() is a function that >>> id(mystr1)
allows getting the 4362322688
memory address >>> mystr1 = mystr1 + "!"
Concatenating two strings generate
of any object >>> id(mystr1)
a new string with a new memory address
4362323008
>>>
String Methods
• Python has quite a few methods that string objects can call
• For example, the split() method can be utilized to split a string into a
list (more on this next lecture) of substrings
• By default, split() will split the string wherever a space occurs
>>> s1 = "Hello, string methods!"
>>> [Link]()
['Hello,', 'string', 'methods!'] Referred to as a list
>>>
String Methods
• The split() function can also be used to split a string at places other
than spaces by supplying the character to split on as a parameter
• For instance, if we have a string of numbers separated by commas, we
could split on the commas as follows:
>>> "32,24,25,57".split(",")
['32', '24', '25', '57']
>>> "32,24,25,57".split()
['32,24,25,57']
>>>
String Methods
• In general, the split() function has the following syntax:
split(Separator, Maxsplit)
Where:
Separator is the delimiter at which the string is split at (if it is not provided,
white space will the separator)
Maxsplit is the number of splits that shall be performed on the string (if it is
not provided, there will be no limit on the number of splits)
String Methods
• Here are some interactive examples:
>>> mystr1 = "topic: string methods" >>> [Link](": ", 0)
>>> [Link](": ") ['topic: string methods: October, 2018']
['topic', 'string methods'] >>> [Link](": ", 1)
>>> mystr2 = mystr1 + ": October, 2018" ['topic', 'string methods: October, 2018']
>>> [Link](": ") >>> [Link](": ", 2)
['topic', 'string methods', 'October, 2018'] ['topic', 'string methods', 'October, 2018']
>>> >>>
Some Other String Methods
Function Meaning
[Link]() Copy of s with only the first character capitalized
[Link](width) Copy of s centered in a field of given width
[Link](sub) Count the number of occurrences of sub in s
[Link](sub) Find the first position where sub occurs in s
[Link](width) Like center, but s is left-justified
[Link]() Copy of s in all lowercase characters
[Link]() Copy of s with leading white space removed
Some Other String Methods
Function Meaning
[Link](oldsub, newsub) Replace all occurences of oldsub in s with newsub
[Link](sub) Like find, but returns the rightmost position
[Link](width) Like center, but s is right-justified
[Link]() Copy of s with trailing white space removed
[Link]() Copy of s with first character of each word capitalized
[Link]() Copy of s with all characters converted to uppercase
Next Lecture…
• Lists