As with any programming language, strings are one of the most important things to know about Python. Also as we have experienced in the other languages so far, strings contain characters. Strings are not picky by any means. They can contain almost anything if used properly. The are also not picky by the amount of characters you put in them. Quick Example!
The type() is awesome. It returns the variable type of whatever is inside the parentheses, which is very useful if you have a few bugs that you can’t figure out or if you haven’t looked a large chunk of code for awhile and don’t know what type the variable is. Back to the amount of characters in a string, we can see even an empty set of “” returns as a string. Strings are powerful and are very easy to declare. Let’s look into some common string methods so you can get your hands dirty.
Common String Methods in Python
- stringVar.count(‘x’) – counts the number of occurrences of ‘x’ in stringVar
- stringVar.find(‘x’) – returns the position of character ‘x’
- stringVar.lower() – returns the stringVar in lowercase (this is temporary)
- stringVar.upper() – returns the stringVar in uppercase (this is temporary)
- stringVar.replace(‘a’, ‘b’) – replaces all occurrences of a with b in the string
- stringVar.strip() – removes leading/trailing white space from string
One of the really cool things about Python is that almost everything can be broken down by index and strings are no different. With strings, the index is actually the character. You can grab just one character or you can specify a range of characters.
Let’s discuss the print (a[1:3]) because it is the easiest to explain. Remember that Python starts all indexes from 0, which would have been the ‘s’ in our variable a. So, we print out ‘tr’ because we printed everything up to our range of 3, but not 3 itself. As for the second example, welcome to a beautiful part of Python. Essentially, specifying a negative number after a : in an index means that you want python to calculate the index starting from the end and moving toward the front aka backwards. So, we tell python that we want everything from the first character to the second to last character. Take a breather, you earned it.