0% found this document useful (0 votes)
14 views24 pages

Python Strings

The document discusses various operations that can be performed on strings in Python. It covers string as a data type, finding length of strings, traversing strings using indexes, while and for loops, string slices, comparison operations, immutability, built-in functions like find(), and the string module. It also provides examples of string assignments involving reversing, checking palindromes, counting characters, checking pangrams, substring operations and more.

Uploaded by

arvindsoren82
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
14 views24 pages

Python Strings

The document discusses various operations that can be performed on strings in Python. It covers string as a data type, finding length of strings, traversing strings using indexes, while and for loops, string slices, comparison operations, immutability, built-in functions like find(), and the string module. It also provides examples of string assignments involving reversing, checking palindromes, counting characters, checking pangrams, substring operations and more.

Uploaded by

arvindsoren82
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 24

STRINGS

COMPOUND DATA TYPE


• Strings are qualitatively different from Integer and Float type.
• Characters which collectively form a String is a Compound Data Type.
For Eg.
fruit = “apple”
letter = fruit[1]
print (letter)
Output : p // (index value starts from 0 as in C & C++)
LENGTH OF STRINGS
• The inbuilt function to find the length of a string is ‘len()’.
For Eg.
fruit = “banana”
len(fruit)
Output : 6
• To get the last letter we might try
length = len(fruit)
last = fruit[length] #ERROR
( because there is no character at 6th place)
LENGTH OF STRINGS (to be
continued…..)

• Right Method to do this is :


length = len(fruit)
last = fruit[length-1]
• Another way to get the elements from last is :
fruit[-1] # yields the last letter
fruit[-2] # yields the second last letter
TRAVERSAL USING WHILE LOOP
• Processing one character at one time.
For Eg.
index = 0
while index < len(fruit):
letter = fruit[index]
print (letter)
index = index + 1
(Take care of the indentation)
TRAVERSAL USING FOR LOOP
• For loop provides us a privilege to access the characters without using
index.
For Eg.
fruit=“apple”
for char in fruit:
print (char)
(Each time through the loop a character is assigned to the
variable char)
STRING SLICES
• A segment of a string is called a slice, i.e. a character.
• The syntax to select a slice from a string is a[n:m], where a contains
strings, n is the starting index and m is the end index.
• Includes the first index and excluding the last index.
Eg:
s= “Peter, Paul, and Mary”
print (s =[0:5]) # Peter
print (s =[7:11]) # Paul
print (s =[17:21]) # Mary
STRING SLICES (to be
continued…..)

fruit = “banana”
fruit[ : 3] #ban
fruit[ 3 :] #ana
fruit[:] ?
STRING COMPARISON
• Equality Comparison
if word ==“banana!”
• Other Comparisons
if word < “banana”:
print ”Your word,”+ word + “,comes before banana.”
elif word > “banana”:
print ”Your word,”+ word + “,comes after banana.”
STRING COMPARISON (to be
continued…..)

• > and < comparison operations are useful for putting words in
alphabetical order:
• Uppercase letters ,numerals and special symbol comes before
Lowercase letters in Python.

• Need to maintain a standard format of the strings.


STRINGS ARE IMMUTABLE
• An existing string cannot be modified.
For Eg :
greeting = "Hello, world!“
greeting[0] = ’J’ # ERROR!
print greeting
Output : Hello, world
STRINGS ARE IMMUTABLE (to be
continued….)

• The Solution of the problem is


greeting = "Hello, world!“
newGreeting = ’J’ + greeting[1:]
print newGreeting
Output : Jello, World

• The original string remains intact.


Creation of Find Function in Strings
• Find function is used to find the index of a particular character inside
the string, else it returns void.
• It is opposite to that of the [] operator.
def find(str, ch):
index = 0
while index < len(str):
if str[index] == ch:
return index
index = index + 1
return -1
LOOPING AND COUNTING
• For and while loops can be used for looping and counting.
• The following code counts the no of times a appears in the string.
fruit = “grapes"
count = 0
for char in fruit:
if char == ’a’:
count = count + 1
print (count)
Output : 1
STRING MODULE
• String module is a package which contains useful functions for
manipulating strings.
• To use the string module we need to import it first by using the
following line of code i.e.
import string
• Find Function : This inbuilt function finds the index of the character in
the string.
fruit = “guava”
index = string.find(fruit,”a”)
Output : 2
STRING MODULE (to be
continued….)

• Find Function :
Try out
string.find(“banana”,”na”) #2
string.find(“banana”,”na”,3) #4, (starts from index 3)
string.find(“bob”,”b”,1,2) #-1, (checks
between 1 to 2
excluding 2 index)
CHARACTER CLASSIFICATION
• Character Classification is a recognition of character (lowercase or
uppercase) or it’s a digit.
• String module provides several constants that are useful for these
purposes.
• string.lowercase contains all the letters that the system considers to be
lowercase.
• string.uppercase contains all the letters that the system considers to be
uppercase.
import string
print string.ascii_lowercase
print string.ascii_uppercase
print string.digits
Three ways to recognize lowercase

Method 1 :
def isLower(ch):
return string.ascii_lowercase.find(ch) != -1
Method 2 :
def isLower(ch):
return ch in string.ascii_lowercase
Method 3 :
def isLower(ch):
return ’a’ <= ch <= ’z’
String Operations
Assignment Questions:
Q1: Write a program in python to reverse a string.
Q2: Write a program in python to check whether a given string is
palindrome or not.
Q3:Write a Python function that accepts a string and calculate the
number of upper case letters and lower case letters.
Sample String : 'The quick Brow Fox'
Expected Output :
No. of Upper case characters : 3
No. of Lower case Characters : 12
Q4:Write a Python function to check whether a string is pangram or
not. Note : Pangrams are words or sentences containing every letter of
the alphabet at least once.
For example : "The quick brown fox jumps over the lazy dog"
Q5: Write a python program to count the occurrence(frequency) of a
particular character in a string.
Q6:Write a Python program to get a string made of the first 2 and the
last 2 chars from a given a string. If the string length is less than 2,
return instead of the empty string. Sample String : 'wakawama'
Expected Result : 'wama'
Sample String : 'wa'
Expected Result : 'wawa'
Sample String : ' w'
Expected Result : Empty String
Q7:Write a Python program to add 'ing' at the end of a given string
(length should be at least 3). If the given string already ends with 'ing'
then add ‘EE' instead. If the string length of the given string is less than
3, leave it unchanged.
Sample String : 'abc'
Expected Result : 'abcing'
Sample String : 'string'
Expected Result : 'stringEE‘
Q8: Write a Python program to find the first appearance of the substring
'not' and 'poor' from a given string, if 'bad' follows the 'poor', replace the
whole 'not'...'poor' substring with 'good'. Return the resulting string.
Sample String : 'The lyrics is not that poor!'
Expected Result : 'The lyrics is good!'
Q10: Write a Python program to get a string from a given string where
all occurrences of its first char have been changed to '$', except the first
char itself.
Sample String : 'restart'
Expected Result : 'resta$t'

You might also like