CS (083) HOLY CROSS SCHOOL, HAZARIBAG KHALID IQBAL
String Manipulation in Python
What is String in Python?
Strings are contiguous series of characters enclosed in single or double quotes. Python doesn‟t have any
separate data type for characters so they are represented as a single character string.
For eg:
>>> s_name = “Amit” # s_name is a variable storing a string.
>>>s = „a‟ #String can also be enclosed in single quotes
How to Create Strings in Python?
Creating strings: To create string enclose the character or sequence of character in Single or Double
Quotes like shown below
>>> s_name = “Amit” #String enclosed in double quotes
>>>s = „a‟ # String enclosed in Single Quotes
We can also use str() function to create string:
N = str () # This function will create an empty string
name = str(1234) # This will create a variable name which store a string “1234”
If we execute the following code:
>>>print(name)
Output will come
1234
CS (083) HOLY CROSS SCHOOL, HAZARIBAG KHALID IQBAL
Traversing Strings in Python:
Traversing a String: It means accessing all the elements of the string one by one using index value.
St = “PYTHON”
Strings in Python
St[1] = Y St[5] = N St[-1] = N St[-6] = P
Iterating through string using for loop:
Traversing the strings in Python using for loop
CS (083) HOLY CROSS SCHOOL, HAZARIBAG KHALID IQBAL
Strings in Python
Operation of Strings in Python
CS (083) HOLY CROSS SCHOOL, HAZARIBAG KHALID IQBAL
Strings in
Python
Membership Operator : there are two membership
operators:
1. „in‟ operator returns True if a substring OUTPUT
is present in main string
2. „not in‟ operator returns True if a substring True
is not present in main string. True
False
str1 = “Welcome”
print(„com‟ in str1)
CS (083) HOLY CROSS SCHOOL, HAZARIBAG KHALID IQBAL
print(„W‟ in str1)
print(„Wel‟ not in str1)
String Comparison : We can compare
OUTPUT
the string using relational/comparison
operator like (>, <, >=, <=, ==, !=)
False
print(“amit” == “Amit”)
True
print(“amit” != “Amit”)
False
print(“blog” > “z”)
Strings in Python
Strings in Python
NOTE: Strings are immutable means that the content of the string cannot be changed
CS (083) HOLY CROSS SCHOOL, HAZARIBAG KHALID IQBAL
We can not change the character in the String
Inbuilt Functions of Strings in Python:
Function
Description Code Output
Name
This function splits
[„I‟ , „am‟ ,
the string into a list of str = ” I am Learning Python”
split() „Learning‟ , „Python‟
string on the basis of print(str.split())
]
delimiter
This function converts
str = ” I am Learning Python” I AM LEARNING
upper() the string into
print(str.upper()) PYTHON
uppercase
This function converts
str = ” I am Learning Python”
lower() the i am learning python
print(str.lower())
string into lowercase
This function replaces a str = ” I am Learning Python”
substring from the main newstr=str.replace
replace() I am Doing Python
string. (“Learning”,”Doing”)
As strings are print(newstr)
immutable
CS (083) HOLY CROSS SCHOOL, HAZARIBAG KHALID IQBAL
so this function creates
a new string
This function return the
str = “I am Learning Python”
find() index of substring in a 2
print(str.find(„am‟))
main string.
This function returns str = “I am Learning Python”
len() 20
the length of the string. print(len(str))
This function is used to str=” I am Learning Python”
remove leading print(len(str)) 25
strip()
and trailing whitespace strnew=str.strip() 20
from the string. print(len(strnew))
This function counts
the number of str=”I am Learning Python”
2
count() occurrences of a print(str.count(„a‟))
3
substring print(str.count(„n‟))
in main string
This function converts
the first alphabet
str=”I am Learning Python”
capitalize() of the string to upper I am learning python
print(str.capitalize())
case and all other
alphabets in small case
This function returns
str=”I am Learning Python”
index() the lowest index 2
print(str.index(„a‟))
of substring in a string.
This function returns str=”I am Learning Python” False (#it contain
isalnum()
True if it‟s made of print(str.isalnum()) spaces)
CS (083) HOLY CROSS SCHOOL, HAZARIBAG KHALID IQBAL
alphanumeric
characters str=”IamLearningPython” True
only. If there is one print(str.isalnum())
space in a string,
this function will
return False.
str=”12345678″ True(#only digits)
This function returns print(str.isdigit())
True if all the
isdigit()
characters
in the string are digits str=”12345678A” False(#contain
otherwise False. print(str.isdigit()) alphabet)
False(#contain upper
str=”I am Learning Python”
case alphabet)
This function returns print(str.islower())
True if all the
islower() characters
in the string are in
lower case str=”i am learning python”
print(str.islower())
True
str=”I am Learning Python” False(#contain small
This function returns print(str.isupper()) case)
True if all the
isupper()
characters in the str=”I AM LEARNING
string are in upper case PYTHON”
print(str.isupper()) True
CS (083) HOLY CROSS SCHOOL, HAZARIBAG KHALID IQBAL
False
str=”I am Learning Python”
print(str.isspace())
This function returns
True if all the str=” “
isspace() True (#contain only
characters in the print(str.isspace())
space)
string is whitespace.
str = “”
print(str.isspace())
False
This function converts
the given string in
title case(first str=”i am learning python” I Am Learning
istitle()
alphabet of each print(str.title()) Python
word is in upper case).
This function converts
the lowercase str=”I am Learning Python” i AM lEARNING
swapcase()
characters to upper print(str.swapcase()) pYTHON
case and vice-versa.
Practice Questions
Q1. Write a program to count the frequency of a character in a string.
str=input("Enter any String")
ch=input("Enter the character")
print(str.count(ch))
CS (083) HOLY CROSS SCHOOL, HAZARIBAG KHALID IQBAL
Q2. Write a program to accept a string and return a string having first letter of each word in capital.
str=input("Enter any String")
print(str.title())
Q3. Write a program to accept a string and display the following:
1. Number of uppercase characters
2. Numbers of lowercase characters
3. Total number of alphabets
4. Number of digits
str=input("Enter any String")
u=0
L=0
d=0
l = len(str)
for i in range(l):
if str[i].isupper():
u = u+1
if str[i].islower():
L=L+1
if str[i].isdigit():
d = d+1
print("Total Upper Case Characters are: ", u)
print("Total Lower Case Characters are: ", L)
print("Total Characters are: ", L + u)
print("Total digits are: ", d)
Q4. Write a program to reverse a string.
str=input("Enter any String")
print(str[::-1])