String Operations
In Python, a string is a sequence of characters. A string is contained within two quotes. You could also use single quotes. A string can be spaces or digits. A string can also be special characters. We can bind or assign a string to another variable. It is helpful to think of a string as an ordered sequence. Each element in the sequence can be accessed using an index represented by the array of numbers.
example:
//negative indexing
-15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
M i c h a e l J a c k s o n
//positive indexing
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Print the first element in the string
print(Name[0])//M
# Print the last element in the string
print(Name[-1])//n
# Find the length of string
len(“Michael Jackson”)//15
# Take the slice on variable Name with only index 0 to index 3
Name[0:4]//’Mich’
# Take the slice on variable Name with only index 8 to index 11
Name[8:12]//’Jack’
# Get every second element. The elments on index 1, 3, 5 …
Name[::2]//’McalJcsn’
# Replace the old substring with the new target substring is the segment has been found in the string
A = “Michael Jackson is the best”
B = A.replace(‘Michael’, ‘Janet’)
B//’Janet Jackson is the best’
# Find the substring in the string. Only the index of the first elment of substring in string will be the output
Name = “Michael Jackson”
Name.find(‘el’)//5
# If cannot find the substring in the string
Name.find(‘Jasdfasdasdf’)//-1
Use a stride value of 2 to print out every second character of the string E:
E = ‘clocrkr1e1c1t’//print(E[::2])
Expressions and Variables
Expressions describe a type of operation the computers perform.Expressions are operations the python performs. For example, basic arithmetic operations like adding multiple numbers.We call the numbers operands, and the math symbols are called operators.