Skip to content

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.

Print

Python has a command called print() that allows strings to be displayed to the screen, regardless of where they are located in the cell.

a=3
b=2
print(a,b)
Output:
3   2
if 5%2 == 0:
    print("5 is even")
else:
    print("5 is odd")   
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.

mystring = 'abc123'
print(mystring[0], mystring[3])
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.

mystring = 'abcdef123456'
print(mystring[2:4])
print(mystring[2:10:3])
Output:
'cd'
'cf3'

We can also use negative integers to index from the other end of the string.

mystring[-1]
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.

mystring = 'abcdef123456'
len(mystring)
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