CH 8 Strings
CH 8 Strings
Introduction
Definition: Sequence of characters enclosed in single, double or triple quotation marks.
Eg. str1=’PYTHON’
str2=”PYTHON”
str3=’’’PYTHON’’’
str4=”””PYTHON”””
Basics of Strings
❖ Strings are immutable in Python. This means it is unchangeable. At the same memory
address the new value cannot be stored.
❖ Each character has its index or can be accessed using its index and is written in square
brackets([ ]).
Eg.
Backward Indexing
>>> str1[0]
‘H’
>>>str1[6]
‘W’
>>>str1[-10]
‘e’
>>>str1[11]
Index Error: String out of range
>>>str1[1+5]
‘W’
>>>str1[1.5]
Type Error: String indices must be an integer.
>>>str1[-n]
‘H’
>>>str1[n-1]
‘d’
❖ Character assignment is not supported in string because strings are immutable.
Eg. str1=”HELLO”
str1[2]=”A”
# It is invalid. Individual letter assignment not allowed in Python.
STRING OPERATORS
1. Basic Operators(+,*)
2. Membership Operators(in, not in)
3. Comparison Operators(==,!=,<,<=,>,>=)
4. Slicing
‘A’ to ‘Z’ 65 to 90
Function Description
Ord(<character>) Returns ordinal value of a character
Chr(<value>) Returns the corresponding character
Eg. >>>ord(‘b’)
98
>>>chr(65)
‘A’
4. String Slicing
The Slice operator slices a string using a range of indices.
Syntax:
String_name[Start:End], where Start and End are integer indices.
It returns a string from the index Start to End.
Eg.
>>>str1[0:11]
‘Hello World’
>>>str1[0:7]
‘Hello W’
>>>str1[-5:-1]
‘Worl
>>>str1[:5]
‘Hello’
>>>str1[6:]
‘World’
>>>str1[-11:-6]
‘Hello’
‘dlrow olleH’
‘WorldHello’
>>>str1[8:]+str1[:8]
‘rldHello Wo’
Slice Operator with step index: Slice operator with strings may have third index which is known as step, it
is optional.
Syntax:
String_name[Start:End:Step]
>>>str1[2:9:2]
‘loWr’
>>>str[-11,-3,3]
‘HlW
Note: In Slicing a string outside the index doesn’t cause index error.
Eg. >>>str1[14]
>>>str1[8:16]
rld
Note: When you are accessing a particular character, index must be valid .If it is out of bound, an index
error will show. But in slicing, it returns a substring or empty string which is valid in sequence.
Traversing a String
We can access each character of a string or traverse a string using for loop and while loop.
print(ch,end = “”)
In the above code, the loop starts from the first character of the string str1 and automatically ends
>>> index = 0
print(str1[index],end = '')
index += 1
Here while loop runs till the condition index < len(str) is True, where index varies from 0 to len(str1) -1.
Built in Functions
Function Name Description Example
len() Returns length of the string >>> str1 = 'Hello World!'
>>> len(str1)
12
capitalize() Converts the first character of the >>> str1 = 'hello World!'
string to a capital (uppercase) letter >>> str1.capitalize()
‘Hello World!’
title() Convert string to title case >>> str1 = 'hello WORLD!'
>>> str1.title()
'Hello World!'
lower() Converts all uppercase characters in a >>> str1 = 'hello WORLD!'
string into lowercase >>> str1.lower()
'hello world!'
upper() Converts all lowercase characters in a >>> str1 = 'hello WORLD!'
string into uppercase >>> str1.upper()
'HELLO WORLD!'
count(str,start,end) Returns the number of occurrences of >>> str1 = 'Hello World! Hello
a substring in the string. Hello'
>>> str1.count('Hello',12,25)
2
>>> str1.count('Hello')
3
find(str,start,end) Returns the lowest index of the >>> str1 = 'Hello World! Hello
substring if it is found otherwise Hello'
returns -1. >>> str1.find('Hello',10,20)
13
>>> str1.find('Hello',15,25)
19
>>> str1.find('Hello')
0
>>> str1.find('Hee')
-1
index(str,start,end) Returns the position of the first >>> str1 = 'Hello World! Hello
occurrence of a substring in a string Hello'
>>> str1.index('Hello')
0
>>> str1.index('Hee')
ValueError: substring not found
endswith() Returns “True” if a string ends with >>> str1 = 'Hello World!'
the given suffix
>>> str1.endswith('World!')
True
>>> str1.endswith('lde')
False
Startswith() Returns True if the given string starts >>> str1 = 'Hello World!'
with the supplied substring otherwise >>> str1.startswith('He')
returns False True
>>> str1.startswith('Hee')
False
isalnum() Checks whether all the characters in a >>> str1 = 'HelloWorld'
given string is alphanumeric or not >>> str1.isalnum()
True
>>> str1 = 'HelloWorld!!'
>>> str1.isalnum()
False
isalpha() Returns “True” if all characters in the >>> str1 = 'HelloWorld'
string are alphabets >>> str1.isalpha()
True
isdigit() Returns “True” if all characters in the >>> str1 = 'HelloWorld'
string are digits >>> str1.isdigit()
False
>>>str2=’123’
>>>str2.isdigit()
True
islower() Checks if all characters in the string >>> str1 = 'hello world!'
are lowercase >>> str1.islower()
True
>>> str1 = '1234'
>>> str1.islower()
False
isupper() Checks if all characters in the string >>> str1 = 'HELLO WORLD!'
are uppercase >>> str1.isupper()
True
>>> str1 = '1234'
>>> str1.isupper()
False
isspace() Returns “True” if all characters in the >>> str1 = ' \n \t \r'
string are whitespace characters >>> str1.isspace()
True
>>> str1 = 'Hello \n'
>>> str1.isspace()
False
istitle() Returns True if the string is non- >>> str1 = 'Hello World!'
empty and title case, i.e., the first >>> str1.istitle()
letter of every word in the string in True
uppercase and rest in lowercase >>> str1 = 'hello World!'
>>> str1.istitle()
False
lstrip() Returns the string after removing the >>> str1 = ' Hello World! '
spaces only on the left of the string >>> str1.lstrip()
'Hello World! ‘
rstrip() Returns the string after removing the >>> str1 = ' Hello World! '
spaces only on the right of the string >>> str1.rstrip()
' Hello World!'
strip() Returns the string after removing the >>> str1 = ' Hello World! '
spaces both on the left and the right >>> str1.strip()
of the string 'Hello World!'
replace(oldstr,newstr) Replaces all occurrences of a >>> str1 = 'Hello World!'
substring with another substring >>> str1.replace('o','*')
'Hell* W*rld!'
join() Returns a concatenated String >>> str1 = ('HelloWorld!')
>>> str2 = '-' #separator
>>> str2.join(str1)
'H-e-l-l-o-W-o-r-l-d-!'
partition() Partitions the given string at the >>> str1 = 'India is a Great
first occurrence of the substring Country'
(separator) and returns the string >>> str1.partition('is')
partitioned into three parts. ('India ', 'is', ' a Great Country')
1. Substring before the separator >>> str1.partition('are')
2. Separator ('India is a Great Country',' ',' ')
3. Substring after the separator
If the separator is not found in the
string, it returns the whole string
itself and two empty strings
split() Returns a list of words delimited by >>> str1 = 'India is a Great
the specified substring. If no delimiter Country'
is given then words are separated by >>> str1.split()
space. ['India','is','a','Great','Country']
>>> str1 = 'India is a Great
Country'
>>> str1.split('a')
['Indi', ' is ', ' Gre', 't Country']
Programs in Strings
1. Program to count and display the number of
vowels,consonants,uppercase,lowercase characters in a string.
Str1=input("Enter a string=")
Vcount=Ccount=Lcount=Ucount=0
for i in Str1:
if i.isalpha():
if i.islower():
Lcount+=1
else:
Ucount+=1
if i in 'aeiouAEIOU':
Vcount+=1
else:
Ccount+=1
print("No. of vowels=",Vcount)
print("No. of consonants=",Ccount)
print("No. of Uppercase characters=",Ucount)
print("No. of Lowercase characters=",Lcount)
OUTPUT:
Enter a string=Python Program
No. of vowels= 3
No. of consonants= 10
No. of Uppercase characters= 2
No. of Lowercase characters= 11
2. Program to input a string and determine whether it is a palindrome or
not.
Str1=input("Enter a string=")
newstr=""
length=len(Str1)
for i in range(-1,-length-1,-1):
newstr+=Str1[i]
if Str1==newstr:
print("The given string is a palindrome")
else:
print("The given string is not a palindrome")
Output:
Enter a string=malayalam
The given string is a palindrome
Str1=input("Enter a string=")
newstr=""
length=len(Str1)
for i in range(-1,-length-1,-1):
newstr+=Str1[i]
print("The reversed string =",newstr)
Output:
Enter a string=python
The reversed string=nohtyp
4. Program to convert the case of characters in a string.
Str1=input("Enter a string=")
newstr=""
for ch in Str1:
if ch.islower():
newstr+=ch.upper()
elif ch.isupper():
newstr+=ch.lower()
else:
newstr+=ch
print("Changed string=",newstr)
OUTPUT:
Enter a string=PYTHON program 3.11
Changed string= python PROGRAM 3.11
str2 += str1[0].upper()
for i in range(1, length):
if i % 2 == 0:
if str1[i].islower():
str2 += str1[i].upper()
else:
str2 += str1[i].lower()
else:
str2 += str1[i]
print("The changed string =", str2)
str1=input("Enter a string=")
count=0
for ch in str1:
if ch==ch1:
count+=1
print(“Number of times character“,ch1,”occurs in the string=”,count)
OUTPUT:
Enter a string=operator
Enter the character to be counted=o
Number of times character o occurs in the string= 2
OUTPUT:
Enter a string=python
After replacing vowels with *= pyth*n
********************