Theory Notes On String
Theory Notes On String
Table of Contents
What is String in Python?
How to Create Strings in Python?
Traversing Strings in Python:
Traversing the strings in Python using for loop
Operation of Strings in Python
Inbuilt Functions of Strings in Python:
Practice Questions
Strings in Python
Strings in Python
NOTE: Strings are immutable means that the content of the string cannot
be changed
This function
str = ” I am Learning I AM
converts
upper() Python” LEARNING
the string into
print(str.upper()) PYTHON
uppercase
This function
replaces a
substring from the str = ” I am Learning
main Python”
I am Doing
replace() string. newstr=str.replace
Python
As strings are (“Learning”,”Doing”)
immutable print(newstr)
so this function
creates
a new string
This function
converts
the first alphabet str=”I am Learning
I am learning
capitalize() of the string to upper Python”
python
case and all other print(str.capitalize())
alphabets in small
case
True(#only
str=”12345678″
This function returns digits)
print(str.isdigit())
True if all the
isdigit() characters
in the string are
str=”12345678A”
digits False(#contain
print(str.isdigit())
otherwise False. alphabet)
str=”I am Learning
False(#contain
This function returns Python”
small case)
True if all the print(str.isupper())
isupper() characters in the
string are in upper str=”I AM LEARNING
case PYTHON”
True
print(str.isupper())
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 str=”I am Learning
i AM lEARNING
swapcase() the lowercase Python”
pYTHON
characters to upper print(str.swapcase())
case and vice-versa.
Functions of Strings in Python
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))
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])