Strings
String literals in python is a sequence of characters surrounded by either single quotation marks, or double quotation marks. 'hello'
is the same as "hello"
. Strings are immutable, once created you cannot change them. Strings can be displayed with the print()
function.
Python has a command called print()
that allows strings to be displayed to the screen, regardless of where they are located in the cell.
Output:
3 2
Output:
5 is odd
String Slicing
Each character of a string is accessible by its index, starting with the first character which has index 0.
Output:
a 1
We can also slice out portions of the string using indexes of the form [i:j:k]
where i
is the starting index, j
is the ending index (not included though), and k
is the step size.
Output:
'cd'
'cf3'
We can also use negative integers to index from the other end of the string.
Output:
'6'
Using these ideas we are able to pull apart all sorts of substrings.
print(mystring[:4]) # start (index 0) to index 3
print(mystring[3:]) # index 3 to end
print(mystring[-3]) # index -3
print(mystring[-3:]) # index -3 to end
Output:
abcd
def123456
4
456
Length
The command len()
can be used to return the length of the string.
Output:
12
String Formatting
A very useful string method for creating strings in order to display to the screen is .format()
. The .format()
method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: { }. The .format()
method returns the formatted string.
myP = 'BC'
myC = 'Canada'
myY = 2022
mystring = 'I am in {}, {}, and it is {}'.format(myP,myC,myY)
print(mystring)
Output:
I am in BC, Canada, and it is 2022