2. 1-2
M.Trupthi, Assistant Professor, Dept. of IT, CBIT 8-2
8.1 Sequences
Concept:
A sequence is an object that holds
multiple items of data, stored one after
the other. You can perform operations
on a sequence, to examine and
manipulate the items stored in it.
3. 1-3
M.Trupthi, Assistant Professor, Dept. of IT, CBIT 8-3
8.2 Working with Strings
Concept:
Python provides several ways to access
the individual characters in a string.
Strings also have methods that allow
you to perform operations on them.
4. 1-4
M.Trupthi, Assistant Professor, Dept. of IT, CBIT 8-4
8.2 Working with Strings
Accessing the Individual Characters in a String
Iterating Over a String with the for Loop
Program 8-1
(count_Ts.py)
for variable in string:
statement
statement
etc.
Eg:
name = 'Juliet'
for ch in name:
print(ch)
5. 1-5
M.Trupthi, Assistant Professor, Dept. of IT, CBIT 8-5
8.2 Working with Strings
Accessing the Individual Characters in a String
Indexing
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]
Figure 8-2 String indexes
8. 1-8
M.Trupthi, Assistant Professor, Dept. of IT, CBIT 8-8
8.2 Working with Strings
Strings Are Immutable
Program 8-2 (concatenate.py)
Figure 8-4 The string
'Carmen' assigned to name
Figure 8-5 The string
'Carmen Brown' assigned
to name
letters = 'abc'
letters += 'def‘ O/p:abcdef
letters = letters + 'def'
11. 1-11
M.Trupthi, Assistant Professor, Dept. of IT, CBIT 8-11
8.2 Working with Strings
String Slicing
P a t t y L y n n 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
12. 1-12
M.Trupthi, Assistant Professor, Dept. of IT, CBIT
8-12
8.2 Working with Strings
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
No te: Invalid indexes do not cause slicing expressions to
raise an exception. Pg 366
14. 1-14
M.Trupthi, Assistant Professor, Dept. of IT, CBIT 8-14
8.2 Working with Strings
String Methods
Table 8-1 Some string testing methods
stringvar.method(arguments)
general format
16. 1-16
M.Trupthi, Assistant Professor, Dept. of IT, CBIT 8-16
8.2 Working with Strings
The Repetition Operator … *
Program 8-8 (repetition_operator.py)
string_to_copy * n
my_string = 'w' * 5
print('Hello' * 5)