Strings in Python

 
Video Tutorials
Artificial Intelligence Tutorial
Machine Learning Projects TutorialPython Video tutorial
Computer Graphics Video TutorialC++ Video Tutorial
Big Data Analytics Video TutorialSoft Computing Video Tutorial
Placement Video TutorialJava Video Tutorial

Video Tutorial on Strings in Python

Strings in Python

The objective of this tutorial is to learn strings in python. The string operations, built-in functions on strings, sliscing operator etc., are discussed indetail with simple programming examples.

Strings are ordered text based data which are represented by enclosing the same in single/double/triple quotes. Usually single quotes are used to create string with one word. The double quotes are used to create a string of multiple words (usually sentence).
And triple quotes are used to create paragraphs.

In [1]:
String0 = 'Taj'
String1 = "Taj Mahal is beautiful"
String2 = '''Taj Mahal is beautiful
and is located ar Agra
India'''
In [2]:
print (String0 , type(String0))
print (String1, type(String1))
print (String2, type(String2))
Taj <class 'str'>
Taj Mahal is beautiful <class 'str'>
Taj Mahal is beautiful
and is located ar Agra
India <class 'str'>

String Indexing

String indexing is used to access the character of a string. The first character of string is indexed at zero.

In [3]:
Str1 = "Taj Mahal is beautiful"
print (Str1[4])
M

Slicing

: is the slicing operator
start_index:end_index

In this case the all the characters starting from start index till one less than the end index are returned.

If start index is not mentioned then characters from 0th index are returned.
If end index is not mentioned then the characters till the end of string are returned.
Finally, If both start and end index are not mentioned then all the charactrs are returned.

In [4]:
Str1 = "Taj Mahal is beautiful"
print (Str1[2:6])
print (Str1[:6])
print (Str1[2:])
print (Str1[:])
j Ma
Taj Ma
j Mahal is beautiful
Taj Mahal is beautiful

Built-in String Functions in Python

find( ) is used to search for a substring in the given string. find function returns the index value of first character of the given substring if that is to found in the string. If substring is not found in the string then find function returns -1. Remember to not confuse the returned -1 for reverse indexing value.
One can also input start index and end index with find( ) function, in such case between start index and one less than end index, the substring is searched.

In [5]:
Str1 = "Taj Mahal is beautiful"
print (Str1.find('al'))
print (Str1.find('am'))
7
-1
In [6]:
Str1 = "Taj Mahal is beautiful"
print (Str1.find('M',1))
print (Str1.find('M',1,6))
print (Str1.find('M', 6, 10))
4
4
-1

index( ) function works in the same way as find( ) function, but the only difference between index and find function is find returns ‘-1’ when the input element is not found in the string but index( ) function throws a ValueError

In [7]:
print (Str1.index('Taj'))
print (Str1.index('Mahal',))
0
4
In [8]:
print (Str1.index('Mahal',10,20))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-d4c04a58d6ce> in <module>()
----> 1 print (Str1.index('Mahal',10,20))

ValueError: substring not found

capitalize( ) function is used to capitalize the first element in the string. In this case all the characters except the first character are converted to lower case and first character of the string to upper case.

In [9]:
Str2 = 'observe the first letter in this sentence.'
print (Str2.capitalize())
Observe the first letter in this sentence.

center( ) is used to center align the string by specifying the field width.

In [10]:
Str1 = " Welcome to python programming"
print (Str1.center(70))
                     Welcome to python programming                    

One can also fill the left out spaces with any other character.

In [11]:
print (Str1.center(70,'-'))
-------------------- Welcome to python programming--------------------

endswith( ) function is used to check if the given string ends with the particular char which is given as input. The start and stop index values can also be specified.

In [12]:
Str1 = " Welcome to python programming"
print (Str1.endswith('y'))
False
In [13]:
Str1 = " Welcome to python programming"
print (Str1.endswith('l',))
print (Str1.endswith('M',,5))
False
False

Similarly, startswith( ) function is used to check if the given string starts with the particular char which is given as input.The start and stop index values can also be specified.

In [14]:
Str1 = " Welcome to python programming"
print (Str1.startswith('y'))
False

count( ) function counts the number of times a given character appears in the given string. The start and the stop index can also be specified or left blank. (These are Implicit arguments which will be dealt in functions)

In [15]:
Str1 = " Welcome to python programming"
print (Str1.count('a',))
print (Str1.count('a',5,10))
1
0

split( ) function is used to convert a string back to a list. Think of it as the opposite of the join() function.

In [16]:
Str1 = " Welcome to python programming"
d = Str1.split()
print (d)
['Welcome', 'to', 'python', 'programming']

lower( ) converts any capital letter to small letter.

In [17]:
Str1 = " Welcome to python programming"
print (Str1.lower())
 welcome to python programming

upper( ) string function converts any lower case letter to uppercase letter. lower( ) string function converts any uppercase letter to lower letter.

In [18]:
Str1 = " Welcome to python programming"
print (Str1.upper())
 WELCOME TO PYTHON PROGRAMMING

replace( ) function replaces the element with another element. By default all the occurance of the found string are replaced with new string. We can pass the number of times the string to be replaced as a parameter to replace function. In the first case all the occurances ot string ‘to’ are replaced with ‘TO’. But in second case only first occurance of ‘to’ is repaced with ‘TO’.

In [19]:
Str1 = " Welcome to python programming to python to"
print (Str1.replace('to','TO'))
print (Str1.replace('to','TO', 1))
 Welcome TO python programming TO python TO
 Welcome TO python programming to python to

strip( ) function is used to delete elements from the right end and the left end which is not required.

In [20]:
f = '    hello      '

If no char is specified then it will delete all the spaces that is present in the right and left hand side of the data.

In [21]:
f.strip()
'hello'

strip( ) function, when a char is specified then it deletes that char if it is present in the two ends of the specified string.

In [22]:
f = '   ***----hello---*******     '
In [23]:
print (f.strip('*'))
   ***----hello---*******     

The asterisk had to be deleted but is not. This is because there is a space in both the right and left hand side. So in strip function. The characters need to be inputted in the specific order in which they are present.

In [24]:
print (f.strip(' *'))
----hello---

lstrip( ) and rstrip( ) function have the same functionality as strip function but the only difference is lstrip( ) deletes only towards the left side and rstrip( ) towards the right.

Summary

This tutorial disusses the the concept od strings in python. The string operations, built-in functions on strings, sliscing operator etc., are discussed indetail with simple programming examples.

Leave a Comment

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