0% found this document useful (0 votes)
20 views19 pages

6 - Strings

The document discusses basic string operations in Python such as defining strings, accessing individual characters in a string using indexing and loops, concatenating strings, slicing strings, and testing, searching and manipulating strings. Some key points covered include that strings are immutable, string slicing syntax and examples, using len() to prevent index errors, and that strings cannot be concatenated with numbers.

Uploaded by

aljazi m
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)
20 views19 pages

6 - Strings

The document discusses basic string operations in Python such as defining strings, accessing individual characters in a string using indexing and loops, concatenating strings, slicing strings, and testing, searching and manipulating strings. Some key points covered include that strings are immutable, string slicing syntax and examples, using len() to prevent index errors, and that strings cannot be concatenated with numbers.

Uploaded by

aljazi m
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/ 19

10/6/2021

www.tvtc.gov.sa

Strings
Pearson Education , Edited by :Nouf Almunyif

Basic String Operations

Pearson Education , Edited by :Nouf Almunyif 2

1
10/6/2021

Basic String Operations


• String: sequence of characters that is used as data
• Must be enclosed in single (') or double (") quote marks
• String literal can be enclosed in triple quotes (''' or """)
• Enclosed string can contain both single and double quotes and can have multiple
lines

Pearson Education , Edited by :Nouf Almunyif 3

Multiline Strings
• You can assign a multiline string to a variable by using three quotes Or
three single quotes:

Pearson Education , Edited by :Nouf Almunyif 4

2
10/6/2021

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

Pearson Education , Edited by :Nouf Almunyif 5

Working with Strings

Pearson Education , Edited by :Nouf Almunyif 6

3
10/6/2021

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]

Pearson Education , Edited by :Nouf Almunyif 7

Accessing the
Individual
Characters in
a String

Pearson Education , Edited by :Nouf Almunyif 8

4
10/6/2021

Accessing the Individual Characters in a String

my_string = ‘Roses are red’


print (my_string[0], my_string[6], my_string[10])
print (my_string[-1], my_string[-2], my_string[-3])

Pearson Education , Edited by :Nouf Almunyif 9

Accessing the Individual Characters in a String

Pearson Education , Edited by :Nouf Almunyif 10

5
10/6/2021

Accessing the Individual Characters in a String


• 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

B o s t o n
     
0 1 2 3 4 5

Pearson Education , Edited by :Nouf Almunyif 11

Accessing the Individual Characters in a String


IndexError Exceptions
• 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
len returns the length of a sequence

B o s t o n
     
0 1 2 3 4 5

Pearson Education , Edited by :Nouf Almunyif 12

6
10/6/2021

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

Pearson Education , Edited by :Nouf Almunyif 13

Strings Are Immutable

Pearson Education , Edited by :Nouf Almunyif 14

7
10/6/2021

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

Pearson Education , Edited by :Nouf Almunyif 15

Working with Strings


• we cannot combine strings and numbers like this:
• Example

Pearson Education , Edited by :Nouf Almunyif 16

8
10/6/2021

Working with Strings


• we cannot combine strings and numbers like this:
• Example

Pearson Education , Edited by :Nouf Almunyif 17

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

Pearson Education , Edited by :Nouf Almunyif 18

9
10/6/2021

String Slicing Pat t y Lynn S m i t h


0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
-16 - 15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 - 2 -1

•full_name = ‘Patty Lynn Smith’


•middle_name = full_name[6:10] # middle_name <= ‘Lynn‘
•first_name = full_name[:5] # first_name <= ‘Patty’
•last_name = full_name[11:] # last_name <= ‘Smith’
•my_string = full_name[:] # my_string <= ‘Patty Lynn Smith’

•my_string = full_name[0:len(full_name)] # my_string <= ‘Patty Lynn Smith’

•last_name = full_name[-5:] # last_name <= ‘Smith’

Pearson Education , Edited by :Nouf Almunyif 19

String Slicing
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

string[start : end : step]

letters = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’
print letters[0:26:2] # ‘ACEGIKMOQSUWY’

Pearson Education , Edited by :Nouf Almunyif 20

10
10/6/2021

Testing, Searching, and Manipulating


Strings

Pearson Education , Edited by :Nouf Almunyif 21

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

Pearson Education , Edited by :Nouf Almunyif 22

11
10/6/2021

Testing Strings with in and not in


in operator determines whether one string is contained in another string

not in operator determines whether one string is contained in another string

Pearson Education , Edited by :Nouf Almunyif 23

String Methods

Pearson Education , Edited by :Nouf Almunyif 24

12
10/6/2021

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

Pearson Education , Edited by :Nouf Almunyif 25

String
Methods

Boolean

Pearson Education , Edited by :Nouf Almunyif 26

13
10/6/2021

String 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

Pearson Education , Edited by :Nouf Almunyif 27

String Methods

Pearson Education , Edited by :Nouf Almunyif 28

14
10/6/2021

String 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
•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

Pearson Education , Edited by :Nouf Almunyif 29

String Methods

Pearson Education , Edited by :Nouf Almunyif 30

15
10/6/2021

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

Pearson Education , Edited by :Nouf Almunyif 31

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

Pearson Education , Edited by :Nouf Almunyif 32

16
10/6/2021

Splitting a String

Pearson Education , Edited by :Nouf Almunyif 33

Splitting a String

Pearson Education , Edited by :Nouf Almunyif 34

17
10/6/2021

format() Read

Pearson Education , Edited by :Nouf Almunyif 35

format() Read

Pearson Education , Edited by :Nouf Almunyif 36

18
10/6/2021

format() Read

Pearson Education , Edited by :Nouf Almunyif 37

‫العنوان الفرعي‬

Pearson Education , Edited by :Nouf Almunyif 38

19

You might also like