You are on page 1of 21

PROGRAMMING AND PROBLEM

SOLVING WITH PYTHON

CHAPTER 7
STRINGS

Copyright © 2018 McGraw Hill Education, All Rights Reserved.

PROPRIETARY MATERIAL © 2018 The McGraw Hill Education, Inc. All rights reserved. No part of this PowerPoint slide may be displayed, reproduced or distributed in any form or
by any means, without the prior written permission of the publisher, or used beyond the limited distribution to teachers and educators permitted by McGraw Hill for their individual
course preparation. If you are a student using this PowerPoint slide, you are using it without permission.
Introduction to Strings
 String is a sequence of characters.

 In Python string is an object of str class.

 In many languages, strings are treated as an array of characters.

 But in Python string is an object of str class.

 The String class has lot many constructors.


The str class
 Strings are the objects of str class
 Create a string using the constructor of str class .
S1=str() #Creates an Empty string Object
S2=str(“Hello”) #Creates a String Object for Hello
 Alternative way to create a string object is by assigning a string
value to a variable.
S1 = “” # Creates a Empty String
S2=”Hello” # Equivalent to S2=str(“Hello”)
 Access the characters of a string one at a time using the index
operator
Python Basic Built-in Functions for String
 min() and max() functions to return largest and smallest character in
a string.
 len() function to return number of characters in a string.
>>> a = "PYTHON"
>>> len(a) #Return length i.e. number of characters in
string a
6
>>> min(a) #Return smallest character present in a string
'H'
>>> max(a) #Return largest character present in a string
'Y'
The Index[] Operator

 The characters in a string can be accessed one at a time through


the index operator.

 The first character of a string is stored at 0th position.

 The last character of a string is stored at position one less than


length of the string.

 Graphical representation how string are stored is shown below.


Continued
Example:
>>> S1="Python"
>>>S1[0] #Access the first element of the string.
'P'
>>>S1[5] #Access the last element of the String.
'n‘
Example:
>>> a='IIT'
>>> a[3]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
a[3]
IndexError: string index out of range
Access Characters via Negative Index

 Negative index accesses the characters from the end of


the string counting in backward direction.
 The index of last character of any non-empty string is
always -1 as shown below.

Example:
 >>> S="PYTHON"
 >>> S[-1]#Access the last character of a String ‘S’
 'N'
Continued
Example:
S="IIT-Bombay"
>>> S[-3]
>>>‘b’
Traversing string with for and while Loop
Loop is used to traverse all characters in a string
Program:-To traverse all the elements of a String using for loop.
S="India"
for ch in S:
print(ch,end="")
Output:
India

Program :-To Traverse every second character of a string using for loop.
S="ILOVEPYTHONPROGRAMMING"
for ch in range(0,len(S),2):#Traverse each Second character
print(S[ch],end=" ")

Output:
I OEYH N R GAM N
Traversing with a while Loop
Programmers can also use while loop to traverse all the elements of a string.

Program : To traverse all the elements of a String using while loop.


S="India"
index=0
while index<len(S):
print(S[index],end="")
index=index+1
Output:
India
Immutable Strings
Character Sequences fall into two categories such as mutable and immutable .
Mutable means changeable and immutable means unchangeable.
So the strings are immutable sequences of characters.
What happens if you try to change the contents of the string?

Example:
Str1="I Love Python"
Str1[0]="U"
print(Str1)

ERROR:
TypeError: 'str' object does not support item assignment

one cannot change the existing string.


The String Operators

 String contains slicing operator, slicing with step sizes operator to obtain subset
of string.
 It also has basic Concatenation ‘+’, ‘in’ and repetition ‘*’ operators.
The following section describes string operators in details

String Slicing Operator [start: end]


The slicing operator returns a subset of a string, called “slice” by specifying two
indices i.e. start and end.
Its syntax is used to return the subset of a string. Syntax is as follows.
Name_of_Variable_of_a_String[Start_Index: End_Index]
Example:
>>> S="IIT-BOMBAY"
>>> S[4:10]#Returns a Subset of a String
'BOMBAY‘
4 to one index less than that of end parameter of slicing operation i.e. 10 - 1 = 9.
String Slicing With Step Size
 A programmer can select every second character from a string.
 This can be possible using “Step Size”.
 In slicing first two parameters are start index and end index.
 Thus, add third parameter as “Step Size” to select a characters from a string
with step size
 Syntax:
 Name_of_Variable_of_a_String[Start_Index:End_Index:Step_Size]
 Example:
>>>S="IIT-BOMBAY"
>>> S[0:len(S):2]
>>>'ITBMA‘
The statement S[0:len(S):2]indicates to select the portion of string which starts
at index 0, ends on index 10 i.e.
The String +, * and in Operators
 The + Operator - The concatenation operator ‘+’ is used to join two
Strings.
Example:
>>> S1="IIT " #The String “IIT” assigned to S1
>>> S2="Delhi"#The String “Delhi” assigned to S1
>>> S1+S2
'IIT Delhi'
 The * Operator - The multiplication(*) operator is used to concatenate the
same string multiple times. It is also called as “repetition operator”.
 Example:
>>> S1="Hello"
>>> S2=3*S1#Print the String “Hello” three times
>>> S2
'HelloHelloHello'
The in and not in Operator
 Both Operators in and not in are used to check whether a string is present in another
string.
 Example:
>>> S1="Information Technology"
#Check if the string “Technology” is present in S1
>>> "Technology" in S1
True

#Check if the string “Technology” is present in S1


>>> "Engineering" in S1
False

>>> S1="Information Technology"


# Check if the string “Hello” is not present in S1
>> "Hello" not in S1
True
String Operations and Comparisions
 The str class provides different basic methods to perform
various operations on String
 It helps to calculate the length of string
 Retrieve the individual characters from the given string
 Compare and concatenate the two different Strings
 Operators such as ==,<,>,<=,>=and != are used to compare the
strings.
 Python compares strings by comparing their corresponding
characters.
Example:
>>> S1="abcd"
>>> S2="ABCD"
>>> S1>S2
True
The split() method

 The split() method returns a list of all the words in the string.

 It is used to break up a string into smaller strings.

>>> Str1="C C++ JAVA Python“ #Assigns names of


Programming languages to Str1

>>>Str1.split()

['C , C++, JAVA, Python']


Methods to convert a String to another String
 String may be present in lowercase, or in uppercase.
 But the string with lower case can also be converted to
uppercase and vice-versa using various methods of str
class.
 Various methods to convert a string from one form to
another are as follows.
 str capitalize() Returns the copy of the string with only
the first character capitalized .
 str swapcase() Returns a copy of this string which convert
upper case character to lower case character and lower
case character to upper case character.
Stripping Unwanted characters from a String
 The python provides various methods to remove white
space characters from the front, end or both the end of a
string.
 Note: The characters such as ‘’, \f,\r, and \n are called
as the white space characters.
 The methods to strip leading and trailing white space
characters are given as follows.
 str lstrip() Returns a string with the leading white space
characters removed.
 str rstrip() Returns a string with trailing white space
characters removed.
Formatting String
 Methods of str Class for formatting characters
 str center(int width) Returns a copy of this string
centered in a field of the given width
 str ljust(int width) Returns a string left justified in a field
of the given width.
 str rjust(int width) Returns a string right justified in a
field of the given width.
Conclusion
 String is a sequence of characters.
 In Python string is an object of str class.
 Each character within the string can be accessed by positive or
negative index.
 Strings are immutable.
 Various inbuilt methods are used to perform various
operations on strings.
 Unwanted characters can be removed by making use of strip()
function.

You might also like