Working With Strings In Python

Hi there. This page will go over some things you can do with strings in Python. String testing methods are not shown here.

(Reference: Starting Out With Python – Second Edition By Tony Gaddis)

 


Indexing In Strings

Each string (text) consists of characters which can be either a letter, symbol or a space. If you want the first character in a string, the index would be 0.

 

 

To search for the last character (letter in this case), the index would be the length of the string minus 1. The minus one is needed as the index starts from 0 and not 1.

 


For Loop: Printing Each Character

 

With a for loop, you can print out each character in a string. The format for a for loop in a string is:

 

With the pineapple example, each character in pineapple can be printed.

 


While Loop: Printing Each Character

Using a while loop to print each character is a little bit more involved. An index counter needs to be set up and inside the while loop the index counter needs to be updated. Not updating the index number will result in an infinite loop in the while loop.

 

 


String Slicing

With string slicing, you can access certain characters within a string. A string has a starting index of 0 just like in Python lists. The format of the string with its indices is:

 

 

There are three ways in obtaining the last two letters in the colour purple.

 


The in and not in Keywords In Strings

With the in and not in keywords, you can check whether a certain string is inside another string. In the examples below, if the word apple is in pineapple I print a certain output and if the word yellow is not in pineapple then something different happens.

 

 

 

 

 

Leave a Reply