Computer Programming - Lecture 8
Computer Programming - Lecture 8
Programming: Lecture
7
Outline
• Strings
Strings
• A string in Python is a sequence of characters. It can be enclosed by either single or double
quotes, although single quotes are more commonly used. For example, the following are all
strings:
'This is a string'
"This is also a string"
Strings
Strings can contain any character, including letters, numbers, punctuation, and whitespace. They
can also contain special characters, such as escape sequences. For example, the following string
contains an escape sequence that represents a newline character:
This is a string
with a newline character
String Operations
• len(): Returns the length of the string.
print(len(“name”)) -> 4
name = "Abel"
print(name[0]) => A
print(name[1]) => b
print(name[2]) => e
print(name[3]) => l
Traversing a string with a while loop
i=0 A
name = "Abebe" b
e
while(i < len(name)): b
print(name[i]) e
i=i+1
Traversing a string using a for loop
A
for letter in name: b
print(letter) e
b
e
Slicing
• A substring of a string is obtained by taking a slice.
• We use the colon operator to get a continuous section of the string
Syntax
[start index:end index]
Outputs
A substring from the start index to
the end index minus 1
Example
s = 'Monty Python'
print(s[0:2]) => Mo
Example
print (s[8:]) =>thon
#if a value is not provided the default start index is 0 and the end index is length - 1
print (s[:]) => Monty Python
print(s[:4]) => Mont