Python 3 – Learn it quick – Strings

Introduction to Strings

In this lesson, we are discussing about Strings and String operations in Python. The strings are sequences of one or more characters, which are variable or a constant. Strings are are surrounded by either single quotation marks, or double quotation marks and they are immutable in nature, which means, the value will not change.

The print finction can be used to print a string. One example is given in this lab.

samplestr = "This is a sample string" print(samplestr) This is a sample string

String Indexing and Slicing in Python

In python, each character in string is mapped to an index and index start with 0, like in the case of arrays.

Positive String Indexing

Please see the below table,

The top row in the below table is a sample string with 16 characters,

THIS IS A STRING

T h i s   i s   a   s t r i n g
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

In this example, the index starts with the letter with index number 0 and last index of the string is G with index number 15. The indexing is applicable to space and any special characters present in the string. Space between THIS and IS is assigned with index number 4 and is the case with other spaces.

Any character present in the string can be accessed by using the index number associated with it.

Example :

 string = "Is this a string?"
string[6]
s

Excercise to identify the postive index of string is below.

string = "Is this a string?" string[16] ?
Negative String Indexing

Negative string indexing is used, if the character needs to be read backwards, which means, if the indexing needs to be done from the last character of a string.

Sample String : IS THIS A STRING?

This will be represented in negative indexing as below,

I S   T H I S   A   S T R I N G ?
-17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

In negative indexing method, the value will be read from last character. Below given is an example,

test = "IS THIS A STRING ?"
test[-6]
T

Let us try it in the below lab,

test = "IS THIS A STRING?" test[-6] T

String Slicing

Portion of a string can be sliced out from the complete string using slicing. Consider a string “Some Apples and Peaches”. Using the slicing, the substring “Apples” can be sliced out. The Slicing is done by creating a range of index numbers separated by a colon [i:j]. The letter i stands for the first character of the slice and letter j stands for the last character of the slice.

To slice “Apples”,

str = "Some Apples and Peaches"
str[5:10]

To create a slice, everything after “and”, from character “a” to form a string “and Peaches”, the indexing will be like this below. The below index will create a subsctring from the character 14 till the end of original string.

 
string = "Some Apples and Peaches"
string[14:]
d Peaches

To create a slice by including all characters from the start till the end of the word “and”, while removing the space and “Peaches”, which means, create a substring “Some Apples an”, the indexing needs to be done like below.

 
string = "Some Apples and Peaches"
string[:14]
Some Apples an

Slicing can also be done using the negative indexing or reverse indexing, which means from the last character of original string. To create a slice “Peaches” using the negative indexing, the code will be like below

 
string = "Some Apples and Peaches"
string[-1:-7]

String Striding

The third character in string denotes a stride. The stride denotes, how many characters need to move forward after the first character from the string. By default, for a string, the stride value is 1.

The below code will print “Apples”.

 
string = "Some Apples and Peaches"
string[5:10:1]

If the stride value is set as two, the output string will change to “pls”,

 
string = "Some Apples and Peaches"
string[5:10:2]

If stride needs to be applied against the complete string and stride value needs to be 2, the output will be “Sm plsnadPahs”. Please see the below example,

 
string = "Some Apples and Peaches"
string[::2]
Sm plsnadPahs

Stride can be done using negative or reverse indexing,

 
string = "Some Apples and Peaches"
string[::-1]
sehcaeP dna selppA emoS

String Functions

Python provides the below string functions, to perform different string operations.

    1. len()
    2. count()
    3. find()
String len Function

The string len function is used to find the length of a string, which means, count number of characters present in the string.

Example :

 
string = "Some Apples and Peaches"
print(string(len))
23
String Count Function

The string count function is used to find the count of or the number of times, a character or a substring or a slice is present in the string.

Example :

Count the number of times the character ‘m’ is present in the below string,

 
string = "Some Apples and Peaches"
print(string.count("m"))
1

Count the number of times the slice ‘Apples’ present in the below string,

 
string = "Some Apples and Peaches"
print(string.count("Apples"))
1

Count the number of times the slice ‘Oranges’ present in the below string,

 
string = "Some Apples and Peaches"
print(string.count("Oranges"))
0
String Find Function

The string find function is used to find the first index or the position of a character or a substring or a slice, present in the string.

Example :

Find the first postion of character ‘p’ in the below string,

 
string = "Some Apples and Peaches"
print(string.find("p"))
6

Find the index of slice ‘Apples’ in the below string. The output will return 5, which is the index of the first character of matching slice.

 
string = "Some Apples and Peaches"
print(string.find("Apples"))
5

If the requirement is to look for a matching substring after nth index position, it can be done like below. In the below example, we are trying to look for the next index position or the presence of slice “Apples”, after it was first found. In the below example, the interpreter will start looking for “Apples” after the index position 10 from the start of string.

 
string = "Some Apples are green and some Apples are red"
print(string.find("Apples",10))
30

The negative or reverse indexing can also be used to find the presence of a string from the last character of a string. To do this, a third value needs to be passed.

 
string = "Some Apples are green and some Apples are red"
print(string.find("Apples",10,-9))
36

Now lets us practice the above lessons in our interactive lab,

def stringcalc(): #Declare the string as global global str str = "Some Apples and Peaches" #Call stringcalc() function stringcalc() #Print string slice print(str[5:10]) #Print string slice after the index 14 print(str[14:]) #Print string slice before index position 14 print(str[:14]) #Print string slice using negative slicing print(str[-8:-1]) #Print string slice using stride value 1 print(str[5:10:1]) #Print string slice using stride value 2 print(str[5:10:2]) #Apply stride value 2 to entire string print(str[::2]) #Apply stride value 2 to entire string print(str[::-1]) #Print the length of string print(len(str)) #Count the presence of character 'm' in the string print(str.count("m")) #Count 'Apples' in the string print(str.count("Apples")) #Count 'Oranges' in the string print(str.count("Oranges")) #Find the first postion of character 'p' in the below string print(str.find("p")) #Find the index of slice 'Apples' in the below string print(str.find("Apples")) #Look for a matching substring after nth index position print(str.find("Apples",10)) #Using negative indexing, find the presence of a string from the last character of a string print(str.find("Apples",10,-9))

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.