Python - Lesson6 - String (Revised)
Python - Lesson6 - String (Revised)
String
Form 4
Python String Basics
In Python code, a string is written within double
quotes, e.g. "Hello", or alternately within single quotes
like 'Hi'. Use the len(s) function to get the length of a
string, and use square brackets to access individual
chars inside the string. The chars are numbered
starting with 0, and running up to length-1.
Python String Basics
s = 'Hello'
print(len(s)) ## 5
## Chars are numbered starting with 0
print(s[0]) ## 'H'
print(s[1]) ## 'e'
print(s[4]) ## 'o' -- last char is at length-1
print(s[5]) ## ERROR, index out of bounds
Python String Basics
For example:
Python String Basics
Python strings are "immutable" which means a string
can never be changed once created. Use + between
two strings to put them together to make a larger
string.
s = 'Hello'
t = 'Hello' + ' hi!' ## t is 'Hello hi!'
String Slices
A "slice" in Python is powerful way of referring to sub-
parts of a string. The syntax is s[i:j] meaning the
substring starting at index i, running up to but not
including index j.
index 0 1 23 4
Hello
String Slices
If the first slice number is omitted, it just uses the start
of the string, and likewise if the second slice number is
omitted, the slice runs through the end of the string.
index 0 1 23 4
Hello
String Slices
Use the slice syntax to refer to parts of a string and +
to put parts together to make bigger strings.
Negative Index
As an alternative, Python supports using negative
numbers to index into a string:
-1 means the last char, -2 is the next to last, and so on.
In other words, -1 is the same as the index len(s)-1,
-2 is the same as len(s)-2. The regular index numbers
make it convenient to refer to the chars at the start of the
string, using 0, 1, etc. The negative numbers work
analogously for the chars at the end of the string with -1,
-2, etc. working from the right side.
Negative Index
Python String Loops
One way to loop over a string is to use
the range(n) function which given a number, e.g. 5,
returns the sequence 0, 1, 2, 3 ... n-1. Those values
work perfectly to index into a string, so the loop for i in
range(len(s)) will loop the variable i through the index
values 0, 1, 2, ... len(s)-1, essentially looking at each
char once.
Python String Loops
Hint:
• The chr() function can return the character corresponding to
the ASCII code.
• Use a For loop to retrieve numbers 0 to 9 first.