Basic String Operations

We will explore the various things you can do with strings before outputting them. There are a few things you can do with strings to fit what you require from them.

Using the len function will return the amount of characters within a string including punctuation and spaces.

print(len(string))

Using the .index function will return the position of the first character that matches your search.

string = "Hello"

print(string.index("e"))

* This will print "1" as the first e is found as the 1st character, keep in mind that Python starts at 0 so H is the 0th character.

Index will always print the FIRST position that the character appears in.

Using the .count function will return the amount of times that your searched letter / word is found.

string = "Hello"

print(string.count("l))

* This will print 2 as there are two l's in the string*

Using the slicing command will allow you to take a snippet of the string, such as only the letters after the 3rd and up to the 9th. You can also make it increment in numbers of your choice so it only prints the letters starting from the 1st, ending at the 10th and skips every other character.

print(string[3:7]

* This will print everything STARTING at the third character and ENDING before the 7th character. This means the 7th character will not be included*

print(string[3:7:2]

* This will print the same as above but will skip every other character.

Using [::-1] will reverse the string and make it back to front.

Using .upper will make the whole string CAPS

Using .lower will make the whole string lower

using startswith and endswith functions will return a true or false result depending on whether or not your string begins or ends with whatever you put within the

Continue to the next lesson.