0% found this document useful (0 votes)
7 views24 pages

Gaddis Python 4e Chapter 08 PPT - Online Exercise - Upload

Chapter 8 discusses various string operations in Python, including basic string manipulation, slicing, and methods for testing and searching strings. It covers concepts such as string immutability, concatenation, and the use of operators like 'in' and 'not in'. Additionally, the chapter provides examples of string methods and how to split strings into lists.

Uploaded by

tjmoe24
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)
7 views24 pages

Gaddis Python 4e Chapter 08 PPT - Online Exercise - Upload

Chapter 8 discusses various string operations in Python, including basic string manipulation, slicing, and methods for testing and searching strings. It covers concepts such as string immutability, concatenation, and the use of operators like 'in' and 'not in'. Additionally, the chapter provides examples of string methods and how to split strings into lists.

Uploaded by

tjmoe24
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/ 24

CHAPTER 8

More
About
Strings

Copyright © 2018 Pearson Education, Inc.


Topics
• Basic String Operations
• String Slicing
• Testing, Searching, and Manipulating Strings

2
Copyright © 2018 Pearson Education, Inc.
Basic String Operations
• Many types of programs perform operations on strings
• In Python, many tools for examining and manipulating strings
• Strings are sequences, so many of the tools that work with sequences work with strings

Slides have accompanying code in blue boxes, such as this.


You can also find accompanying code online here:
https://repl.it/@KritiChauhan/Ch8Strings

3
Copyright © 2018 Pearson Education, Inc.
Accessing the Individual Characters in a String
• To access an individual character in a string:
• Use a for loop
• Format: for character in string:
• Useful when need to iterate over the whole string, such as to count the occurrences of
a specific character
• Use indexing
• Each character has an index specifying its position in the string, starting at 0
• Format: character = my_string[i]

name = 'Juliet'
for ch in name:
print(ch)

4
Copyright © 2018 Pearson Education, Inc.
name = 'Juliet'
for ch in name:
print(ch)

5
Copyright © 2018 Pearson Education, Inc.
Compare code segments
• Code segments are not the same!!
• Outputs of both segments are different.

• Each iteration of for loop on the left (code in blue) prints out each letter of the string referenced
by ‘name’
• While each iteration of for loop on the right (code in red) prints out the string referenced by
‘name’!

name = 'Juliet'
name = 'Juliet'
for ch in name:
for ch in name:
ch = 'X'
print(ch)
print(name)

6
Copyright © 2018 Pearson Education, Inc.
Program 8-1
• Program is on Moodle as count_Ts.py
• Program is on repl.it: https://repl.it/@KritiChauhan/Ch8Strings as file s81p81_count_Ts.py (in left
panel)

# This program counts the number of times


# the letter T (uppercase or lowercase)
# appears in a string.

def main():
# Create a variable to use to hold the count.
# The variable must start with 0.
count = 0

# Get a string from the user.


my_string = input('Enter a sentence: ')

# Count the Ts.


for ch in my_string:
if ch == 'T' or ch == 't':
count += 1

# Print the result.


print('The letter T appears', count, 'times.')

# Call the main function.


main()

7
Copyright © 2018 Pearson Education, Inc.
Accessing the Individual Characters in a String
(cont’d.)
• Indexes are assigned just like they are with lists – starting with 0 for the leftmost character

my_string = 'Roses are red'


ch = my_string[6]
print(ch)

my_string = 'Roses are red'


print(my_string[0], my_string[6], my_string[10])

my_string = 'Roses are red'


print(my_string[-1], my_string[-2], my_string[-13]) 8
Copyright © 2018 Pearson Education, Inc.
Accessing the Individual Characters in a String
(cont’d.)
• IndexError exception will occur if:
• You try to use an index that is out of range for the string
Likely to happen when loop iterates beyond the end of the string
• len(string) function can be used to obtain the length of a string
Useful to prevent loops from iterating beyond the end of a string

#IndexError example:
print('example1')
city = 'Boston'
print(city[6])

#IndexError example:
print('\nexample2')
city = 'Boston'
index = 0
while index < 7:
print(city[index])
index += 1

#IndexError loop corrected:


city = 'Boston'
index = 0
while index < len(city):
print(city[index])
index += 1

9
Copyright © 2018 Pearson Education, Inc.
String Concatenation
• Concatenation: appending one string to the end of another string
• Use the + operator to produce a string that is a combination of its operands
• The augmented assignment operator += can also be used to concatenate strings
• The operand on the left side of the += operator must be an existing variable; otherwise,
an exception is raised

print("Concatenating two strings:")


message = 'Hello ' + 'world'
print(message)

print("Concatenating three strings")


first_name = 'John'
last_name = 'Smith'
full_name = first_name + ' ' + last_name
print(full_name)

print("Concatenating using '+=' operator")


letters = 'abc'
letters += 'def'
print(letters)

10
Copyright © 2018 Pearson Education, Inc.
Strings Are Immutable
• Strings are immutable
• Once they are created, they cannot be changed
• Concatenation doesn’t actually change the existing string, but rather creates a new
string and assigns the new string to the previously used variable
• Cannot use an expression of the form
• string[index] = new_character
• Statement of this type will raise an exception

name = 'Carmen' # Assign 'Bill' to friend.


print('The name is',name) friend = 'Bill'
name = name + ' Brown' # Can we change the first character to 'J'?
print('Now the name is', name) friend[0] = 'J' # No, this will cause an error!

11
Copyright © 2018 Pearson Education, Inc.
Recap
• Topics covered in this section:
• String – for loop over each character
• Indexing
• Negative indexing
• len()
• Concatenation ‘+’ operator
• Immutability (strings)

12
Copyright © 2018 Pearson Education, Inc.
String Slicing
• Slice: span of items taken from a sequence, known as substring
• Slicing format: string[start : end]
• Expression will return a string containing a copy of the characters from start up to,
but not including, end
• If start not specified, 0 is used for start index
• If end not specified, len(string) is used for end index
• Slicing expressions can include a step value and negative indexes relative to end of string
• Slicing format, with step value: string[start : end : step]
• Invalid indexes do not cause slicing expressions to raise exception.
• If the end index specifies a position beyond the end of the string, Python will use the length
of the string instead.
• If the start index specifies a position before the beginning of the string, Python will use 0
instead.
• If the start index is greater than the end index, the slicing expression will return an empty
string.

Run example code on repl.it: https://repl.it/@KritiChauhan/Ch8Strings


Filename: s82_slicing.py

13
Copyright © 2018 Pearson Education, Inc.
Testing, Searching, and Manipulating

Strings
You can use the in operator to determine whether one string is contained in another string
• General format: string1 in string2
• string1 and string2 can be string literals or variables referencing strings
• Similarly you can use the not in operator to determine whether one string is not contained in
another string

#in, not in operators


text = 'Four score and seven years ago'
if 'seven' in text:
print('The string "seven" was found.')
else:
print('The string "seven" was not found.')

names = 'Bill Joanne Susan Chris Juan Katie'


if 'Pierre' not in names:
print('Pierre was not found.')
else:
print('Pierre was found.')

14
Copyright © 2018 Pearson Education, Inc.
String Methods
• Strings in Python have many types of methods, divided into different types of operations
• General format:
mystring.method(arguments)
• Some methods test a string for specific characteristics
• Generally Boolean methods, that return True if a condition exists, and False otherwise

user_string = input('Enter a string: ')

print('This is what I found about that string:')

# Test the string.


if user_string.isalnum():
print('The string is alphanumeric.')
if user_string.isdigit():
print('The string contains only digits.')
if user_string.isalpha():
print('The string contains only alphabetic characters.')
if user_string.isspace():
print('The string contains only whitespace characters.')
if user_string.islower():
print('The letters in the string are all lowercase.')
if user_string.isupper():
print('The letters in the string are all uppercase.')

15
Copyright © 2018 Pearson Education, Inc.
String Testing Methods

16
Copyright © 2018 Pearson Education, Inc.
String Modification Methods
• Some methods return a copy of the string, to which modifications have been made
• Simulate strings as mutable objects
• String comparisons are case-sensitive
• Uppercase characters are distinguished from lowercase characters
• lower and upper methods can be used for making case-insensitive string comparisons

again = 'y'
while again.lower() == 'y':
print('Hello')
print('Do you want to see that again?')
again = input('y = yes, anything else = no: ')

again = 'y'
while again.upper() == 'Y':
print('Hello')
print('Do you want to see that again?')
again = input('y = yes, anything else = no: ')

17
Copyright © 2018 Pearson Education, Inc.
String Modification Methods (cont’d.)

18
Copyright © 2018 Pearson Education, Inc.
String Search & Replace Methods
• Programs commonly need to search for substrings
• Several methods to accomplish this:
• endswith(substring): checks if the string ends with substring
• Returns True or False
• startswith(substring): checks if the string starts with substring
• Returns True or False

filename = input('Enter the filename: ')


if filename.endswith('.txt'):
print('That is the name of a text file.')
elif filename.endswith('.py'):
print('That is the name of a Python source file.')
elif filename.endswith('.doc'):
print('That is the name of a word processing document.')
else:
print('Unknown file type.')

19
Copyright © 2018 Pearson Education, Inc.
String Search & Replace Methods

(cont’d.)
Several methods to accomplish this (cont’d):
• find(substring): searches for substring within the string
• Returns lowest index of the substring, or if the substring is not contained in the string,
returns -1
• replace(substring, new_string):
• Returns a copy of the string where every occurrence of substring is replaced with
new_string

string = 'Four score and seven years ago'


position = string.find('seven')
if position != -1:
print('The word "seven" was found at index', position)
else:
print('The word "seven" was not found.')

string = 'Four score and seven years ago'


new_string = string.replace('years', 'days')
print(new_string)

20
Copyright © 2018 Pearson Education, Inc.
String Search & Replace Methods
(cont’d.)

21
Copyright © 2018 Pearson Education, Inc.
The Repetition Operator
• Repetition operator: makes multiple copies of a string and joins them together
• The * symbol is a repetition operator when applied to a string and an integer
• String is left operand; number is right
• General format: string_to_copy * n
• Variable references a new string which contains multiple copies of the original string

22
Copyright © 2018 Pearson Education, Inc.
Splitting a String
• split method: returns a list containing the words in the string
• By default, uses space as separator
• Can specify a different separator by passing it as an argument to the split method

#split() method with no argument


#Default: spaces as separator
# Create a string with multiple words.
my_string = 'One two three four'
# Split the string.
word_list = my_string.split()
# Print the list of words.
print(word_list)

print('\nCode segment: ',code_segment)


code_segment+=1

#split() method with separator '/'


date_string = '11/26/2018'
date_list = date_string.split('/')
print(date_list)
print('Month:', date_list[0])
print('Day:', date_list[1])
print('Year:', date_list[2])

23
Copyright © 2018 Pearson Education, Inc.
Summary
• This chapter covered:
• String operations, including:
• Methods for iterating over strings
• Repetition and concatenation operators
• Strings as immutable objects
• Slicing strings and testing strings
• String methods
• Splitting a string

24
Copyright © 2018 Pearson Education, Inc.

You might also like