String Revision
String Revision
COMPUTER SCIENCE
STRINGS 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:
Strings in Python
St[1] = Y St[5] = N St[-1] = N St[-6] = P
Strings in Python
str1 = “Welcome”
print(‘com’ in str1)
print(‘W’ in str1)
print(‘Wel’ not in str1)
Strings in Python
NOTE: Strings are immutable means that the content of the string cannot be
changed
This function
converts str = ” I am Learning Python” I AM LEARNING
upper()
the string into print(str.upper()) PYTHON
uppercase
This function
converts the str = ” I am Learning Python”
lower() i am learning python
string into print(str.lower())
lowercase
This function
replaces a
substring from the
str = ” I am Learning Python”
main
newstr=str.replace
replace() string. I am Doing Python
(“Learning”,”Doing”)
As strings are
print(newstr)
immutable
so this function
creates
a new string
This function
str = “I am Learning Python”
len() returns the length of 20
print(len(str))
the string.
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
True if it’s made of str=”I am Learning Python”
alphanumeric print(str.isalnum()) False (#it contain spaces)
isalnum() characters
only. If there is one str=”IamLearningPython” True
space in a string, print(str.isalnum())
this function will
return False.
This function
converts
the given string in
title case(first str=”i am learning python”
istitle() I Am Learning Python
alphabet of each print(str.title())
word is in upper
case).
This function
converts
str=”I am Learning Python” i AM lEARNING
swapcase() the lowercase
print(str.swapcase()) pYTHON
characters to upper
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())