String Functionality
fstring = "-- {} --".format(500)
print(fstring)
You can pass more than one variable.
fstring = "-- {} {} --".format(500, "ABC")
print(fstring)
Note that you can't add a string and an integer together normally. The code below will break because they are two different types of variables.
#This will break
print("A"+1)
You can, however, convert an integer to a string using the function str(). This will change the type to string.
#You can add a string and a number by converting
print("A"+str(1))
Likewise, a string could be converted to an integer by calling int() on a string. This will only work if the string could be a valid integer!
#int() converts a variable to an integer
int("1")+2
String Indexing¶
In python, as well as other computer programming languages, we use indices to keep track of different pieces of data. These indices in python begin at 0 as the first element, followed by 1, 2, etc. By passing [i] where i is an index number, we get back the value at that index. For example to get the first letter of the string in "Hello World", we need to pass [0].
#Create the variable
s = "Hello World"
#Grab the first character, which is the letter H
print(s[0])
Likewise, the second element is found by calling [1].
#Get the second element
print(s[1])
You can also get a range of elements by calling [i1:i2] where i1 is the first element to include, and all elements from i1 to i2 - 1 are included. So i1:i2 means all elements from i1 to i2 excluding i2. In the following example, [0:2] returns the first and second characters.
#Get the first and second characters
print(s[0:2])
#Here i1=0 and i2=1, so we get only the first element
print(s[0:1])
#Grab the second and third element
print(s[1:3])
If you leave out i1, it means grab all elements to the left of i2. It is the same as saying i1=0.
#Leaving out the left index gives us everything up to but not including the right index
print(s[:3])
Likewise, leaving out i2 gives everything to the right of i1 including i1.
#Leaving out the right index gives us everything from the left index on
print(s[3:])
If, instead of finding the largest index and subtracting, we wanted to have a simple way to say the last, second to last etc. index, we would use negative indexing. To get everything except the last element, we could use -1.
print(s[:-1])
Likewise, -2 stands for the second to last element.
print(s[:-2])
If we wanted to get the last five letters of a string:
print(s[-5:])
Finding the length of a string¶
The len() function will return back the length of a string.