0% found this document useful (0 votes)
8 views43 pages

Chapter 7 - Strings

Chapter 7 covers strings in Python, explaining their definition as sequences of characters, their immutability, and various operations such as indexing, slicing, and concatenation. It also discusses string comparison, methods, and the use of operators like 'in' for substring checks. The chapter emphasizes the importance of built-in string methods for efficient string manipulation.

Uploaded by

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

Chapter 7 - Strings

Chapter 7 covers strings in Python, explaining their definition as sequences of characters, their immutability, and various operations such as indexing, slicing, and concatenation. It also discusses string comparison, methods, and the use of operators like 'in' for substring checks. The chapter emphasizes the importance of built-in string methods for efficient string manipulation.

Uploaded by

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

Chapter 7: Strings

Outline

• String as a sequence
• Indexing
• Mutability and Immutability
• Searching
• String Comparison

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 2


What is a String?
• a string, the most popular data type in python, is a sequence of characters
enclosed within single quotes, or double quotes or triple single quotes or
triple double quotes; and can easily be created as such
• When a string contains numbers, it is still a string
• Strings are immutable, meaning once a string is created, it cannot be
changed.
• Python provides a wide range of operations and methods for working with
strings.

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 3


Creating strings
• # Single and double quotes
string1 = 'Hello, World!'
string2 = "Hello, World!"
• # Triple quotes for multi-line strings
string3 = '''Hello,
World!'''
string4 = """Hello,
World!""“
What will print statement on each string output?
05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 4
Traversing
• Computations on string start at the beginning, select each character
in turn, do something to it, and continue until the end.
• This pattern of processing is called a traversal.
• The iteration variable, letter “iterates” though the string and the
block (body) of code is executed once for each value the iteration
variable assumes in the sequence
• Traversal for loop:
for letter in 'banana' :
print(letter) b a n a n a
• What will be the output?
05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 5
Looking inside
• We can get at any single character in a string using an index specified in square brackets
>>> fruit = 'banana‘
>>> print(fruit[1]) # prints what?
Indexing operator
• The expression in brackets is called an index
• The index value must be an integer and starts at zero
• And the largest index is length – 1, where length=len(string at hand)
>>> fruit = 'banana'
>>> letter = fruit[0]
>>> print(letter) # print b
>>> length = len(fruit)
>>> w = fruit[length - 1]
>>>print(w) #prints a
>>> print(fruit[-1]) # what will be printed?
05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 6
Indexing
▪ The first character of a string has index 0, thus the indexing could be 0, 1, 2, …
length-1, where length is the length of the string
>>> greeting = 'hello world'
>>> greeting[0]
'h'
>>> 'hello world'[0]
'h'
▪ You can also count back from the end of a string, beginning with -1; the indexing
becomes -1, -2, -3, … (-)length
>>> greeting = 'hello, world'
>>> greeting[-1]
'd'
>>> 'hello world'[-1]
'd‘
>>>greeting[-11] # same as greeting[0]
‘h’

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 7


Traversal using while loop
fruit = ‘banana’
index = 0
while (index < len(fruit):
print(fruit[index])
index+=1
What will be printed?

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 8


Slicing
•A substring of a string is obtained by taking a slice.
•Need to get continuous section of a string using a colon operator.
>>> s = 'Monty Python'

M o n t y P y t h o n
>>> print(s[0:2])
Mo
>>>print(s[:2]) #What will be printed?
>>>print(s[5:]) # What will be printed?
05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 9
Slicing cont’d
▪ You can use indexes to slice (extract a piece of) a string
▪ aStr[i:j] is the substring that begins with index i and ends with (but does not
include) index j H E L L O , W O R L D
>>> greeting = ‘HELLO, WORLD'
>>> greeting[1:3] 0 1 2 3 4 5 6 7 8 9 10 11
'EL'
>>> greeting[-3:-1] -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
'RL'
▪ omit begin or end to mean 'as far as you can go'
>>> print(greeting[:4], greeting[7:])
HELL WORLD
▪ aStr[i:j:k] is the same, but takes only every k-th character
>>> greeting[3:10:2]#steps by 2, picking every other character
'L,WR‘
Takeaway exercise: make it step by 3

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 10


Slice by step example
• Let's say we have these toy cars in a line:
• Each letter is a different car.
• Now, how can we pick certain cars from this line? A B C D E F G H I J K L M
• we can use slicing with steps.
0 1 2 3 4 5 6 7 8 9 10 11 12
• Starting Point:
•Imagine you want to start picking cars from the first car.
•Your starting point is the first car, which we call car ‘A’
• Ending Point:
• You want to stop picking cars before a certain car.
• Let's say we want to stop before car, ‘M’
• Step:
• The step is how many cars you want to skip each time you pick a car.
• If you want to pick every second car, it means you take one car, skip one, take the next, skip one, and so on.

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 11


Implemented:

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 12


Takeaway Exercise

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 13


A character to far
>>>fruit = ‘banana’
>>>print(fruit[6])
Traceback (most recent call last):
File "<stdin>", line 1, in <module> IndexError: string index out of range

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 14


String concatenation
# done using the + operator
string1 = "Hello"
string2 = "World"
combined = string1 + " " + string2
print(combined) # prints the text "Hello World"

# done using the join method


words = ["Hello", "World"] # list
combined = " ".join(words)
print(combined)# prints the text "Hello World"

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 15


Looping and counting
• The following program counts the number of times the letter a appears
in a string:

• Takeaway Exercise: Encapsulate this code in a function named count,


and generalize it so that it accepts the string and the letter as
arguments.

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 16


The in operator
•The keyword in is a Boolean operator that takes two
strings and returns True if the first appears as a
substring in the second:
>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 17


String comparison
• The comparison operators work on strings.
• To see if two strings are equal:
if word == 'banana':
print('All right, bananas.')
• Other comparison operations are useful for putting words in alphabetical order:
word = input(“Please enter your word”)
if word < 'banana':
print('Your word,' + word + ', comes before banana.')
elif word > 'banana':
print('Your word,' + word + ', comes after banana.')
else: print('All right, bananas.')

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 18


String comparison cont’d
• Note that Python is case sensitive.
• All the uppercase letters come before all the lowercase letters, so:
Your word, Pineapple, comes before banana.
• A common way to address this problem is to convert strings to a
standard format, such as all lowercase, before performing the
comparison.
• Takeaway question: How do you convert a string into all lowercase?

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 19


string methods
• Strings are an example of Python objects.
• An object contains both data (the actual string itself) and methods,
which are effectively functions that are built into the object and are
available to any instance of the object.
• Python has a function called dir which lists the methods available for
an object.
• The type function shows the type of an object and the dir function
shows the available methods (next slide)

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 20


String methods
•['capitalize', 'casefold', 'center', 'count', 'encode',
'endswith', 'expandtabs', 'find', 'format', 'format_map',
'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'maketrans', 'partition', 'removeprefix', 'removesuffix',
'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title', 'translate', 'upper', 'zfill']

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 21


String commands cont’d
• You can access the string methods by dot operator
• your editor might pop up a selection window
— typically by pressing Tab — showing all the methods

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 22


String Methods cont’d
▪ A method is a function that is bundled together with a particular type of
object
▪ A string method is a function that works on a string

▪ This is the syntax of a method:

anObject.methodName(parameterList)
▪ For example,

>>> 'avocado'.index('a')
0
• returns the index of the first 'a' in 'avocado'
▪ You can also use a variable of type string

>>> fruit = 'avocado'


>>> fruit.index('a')
0

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 23


String Methods cont’d
▪ Python has many very useful string methods
▪ You should always look for and use an existing string method before coding it
again for yourself. Here are some
s.capitalize()
s.count()
s.endswith() / s.startswith()
s.find() / s.index()
s.format()
s.isalpha()/s.isdigit()/s.islower()/s.isspace()
s.join()
s.lower() / s.upper()
s.replace()
s.split()
s.strip()

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 24


The split() method
▪ The string method split() lets us separate a string into useful parts
∙ Common use: splitting a sentence into its words

▪ Splits by space character by default,

▪ but you can give it a different 'separator' string

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 25


The strip() method
• The string method strip() “cleans” the edges of a string by removing
the character(s) you specify (default: spaces)

• Takeaway question: Why is the “!” not removed in the above output?
• The string module contains a useful variable for this, called
punctuation (like how the math module has pi)

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 26


The split() and strip() together
▪ The split method is useful for extracting words, and the strip method is
useful for cleaning them up
▪ Remember that strip() is a string method, not a list method

• So, how can we clean up every word in a sentence, once we've split it?
05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 27
split() and strip() together cont’d
▪ The strip() method works on one “word” at a time
▪ So, take it one word at a time

• Here items in the list are string each


• Takeaway question: why can't we just use the replace() method to
get rid of punctuation like this?
05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 28
Method parameters
▪ Like any function, a method has zero or more parameters
▪ Even if the parameter list is empty, the method still works on the
'calling' object:

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 29


Method parameters cont’d
• The islapha () method in python returns ‘True’ if all the characters in
a string are alphabetic and there is at least one character in the string.
Otherwise, it returns ‘False’
• Alphabetic characters are those defined in the Unicode character
database as “Letter,” including both uppercase and lowercase letters.

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 30


Method parameters cont’d
▪ The replace() method takes two or three parameters: mandatory:
‘old’ and ‘new’; and ‘count’ (optional)
▪ If ‘count’ is not provided, all occurrences of ‘old’ will be replaced by ‘new’
▪ If ‘count’ is provided, only the first ‘count’ occurrences of ‘old’ will be
replaced with ‘new’
▪ Example:

▪ How to replace only the second and the fifth occurrence of ‘saw’ with
‘SOW’, to output: I saw a SOW cutting a saw. I never saw such a SOW!
▪ (next slide)

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 31


Check it!

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 32


Strings are immutable
▪ A string is immutable -- once created it can not be modified
▪ Any operation that appears to modify a string actually creates a new string; the original
string is not changed

>>> aStr = 'my cat is catatonic'


>>> newStr = aStr.replace('cat', 'dog')
>>> newStr
'my dog is dogatonic'
>>> aStr
'my cat is catatonic'
▪ However, you can associate the old string name with the new object
>>> aStr = 'my cat is catatonic'
>>> aStr = aStr.replace('cat', 'dog')
>>> aStr
'my dog is dogatonic'

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 33


Strings and the print () function
▪ The print() function always prints a string. The input() function
always inputs a string.
▪ Every object in Python has a string representation. Therefore, every
object can be printed.
▪ When you print a number, a list or a function it is the string
representation of the object that is printed
▪ print() takes 0 or more arguments and prints their string
representations, separated by spaces

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 34


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

▪ By default, print() ends its output


with a newline ('\n')

▪ You can change this, for example,


to a hyphen or a white space

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 35


The string format() method
▪ The format() method allows you to create formatted strings by
embedding expressions inside string literals, using curly braces {} as
placeholder and allows flexible formatting options
▪ format() can take multiple arguments, which are inserted into the
placeholders in the string

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 36


The in and not in operators
• The in operator tests for membership. When both of the arguments to
in are strings, in checks whether the left argument is a substring of the
right argument

• Note that a string is a substring of itself, and the empty string is a


substring of any other string.

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 37


The in and not in operators cont’d
• The not in operator returns the logical opposite results of in:

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 38


Takeaway Exercises
1. Combining the in operator with string concatenation using +, and
write a function that removes all the vowels from a string
2. What is the result of each

3. Write a function that recognizes palindromes.

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 39


Takeaway Exercises cont’d
1. Write a function that counts how many times a substring occurs in a
string which responds as follows when called”

2. Write a function that removes the first occurrence of a string from


another string, responding as follows when called:

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 40


Takeaway Exercises cont’d
1. Take the following Python code that stores a
string:
str = “X-DSPAM-Confidence:0.8475”
Use find and string slicing to extract the portion of the
string after the colon character and then use the float
function to convert the extracted string into a floating
point number.
2. Explore the built in functions defined in the
string module
05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 41
Takeaway Exercises cont’d
1. Write a Python program to print the index of a character in a string.
Sample string: w3resource
Expected output:
Current character w position at 0
Current character 3 position at 1
Current character r position at 2
2. Explore string tutorial and exercises on:
https://www.w3schools.com/python/python_strings.asp

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 42


End of Chapter 7

05-Sep-24 Computer Programming with Python/Chapter7_Strings/Lemlem H 43

You might also like