Strings in Python Class 11 Notes
Strings in Python Class 11 Notes
Strings
A string is a group of one or more UNICODE characters in sequence. A letter,
number, space, or any other sign may be used as the character in this situation. One
or more characters can be enclosed in a single, double, or triple quote to produce a
string.
Example –
Note – Python accepts single (‘), double (“), triple (”’) or triple(“””) quotes to
denote string literals. Single quoted strings and double quoted strings are equal.
Triple quotes are used for contain special characters like TAB, or NEWLINES.
String is Immutable
A string is an immutable data type. It means that the contents of the string cannot
be changed after it has been created. An attempt to do this would lead to an error.
String Operations
Concatenation
Output:
Hello World!
Repetition
Python allows us to repeat the given string using repetition operator which is
denoted by symbol *.
Output:
>>> str1 * 5
‘HelloHelloHelloHelloHello’
Membership
Python has two membership operators ‘in’ and ‘not in’. The ‘in’ operator takes two
strings and returns True if the first string appears as a substring in the second
string, otherwise it returns False.
In
Not In
Slicing
>>> str1[3:20]
‘lo World!’
>>> str1[7:2]
Traversing a String
We can access each character of a string or traverse a string using for loop and
while loop.
In the above code, the loop starts from the first character of the string str1 and
automatically ends when the last character is accessed.
Here while loop runs till the condition index < len(str) is True, where index varies
from 0 to len(str1) -1.
There are numerous built-in functions in Python that let us operate with strings. a
few of the most popular built-in functions for manipulating strings.
len()
5
title()
Returns the string with first letter of every word in the string in uppercase and rest
in lowercase
lower()
upper()
Returns number of times substring str occurs in the given string. If we do not give
start index and end index then searching starts from index 0 and ends at length of
the string.
>>> str1.count(‘Hello’,12,25)
2
>>> str1.count(‘Hello’)
3
Returns the first occurrence of index of substring str occurring in the given string.
If we do not give start and end then searching starts from index 0 and ends at
length of the string. If the substring is not present in the given string, then the
function returns -1
Same as find() but raises an exception if the substring is not present in the given
string
Returns True if the given string ends with the supplied substring otherwise returns
False
True
>>> str1.endswith(‘!’)
True
>>> str1.endswith(‘lde’)
False
startswith()
Returns True if the given string starts with the supplied substring otherwise returns
False
isalnum()
Returns True if characters of the given string are either alphabets or numeric. If
whitespace or special symbols are part of the given string or the string is empty it
returns False
islower()
Returns True if the string is non-empty and has all lowercase alphabets, or has at
least one character as lowercase alphabet and rest are non-alphabet characters
8
isupper()
Returns True if the string is non-empty and has all uppercase alphabets, or has at
least one character as uppercase character and rest are non-alphabet characters
isspace()
9
Returns True if the string is non-empty and all characters are white spaces (blank,
tab, newline, carriage return)
istitle()
Returns True if the string is non-empty and title case, i.e., the first letter of every
word in the string in uppercase and rest in lowercase
lstrip()
Returns the string after removing the spaces only on the left of the string
rstrip()
Returns the string after removing the spaces only on the right of the string
strip()
10
Returns the string after removing the spaces both on the left and the right of the
string
replace(oldstr, newstr)
join()
Returns a string in which the characters in the string have been joined by a
separator
partition()
Partitions the given string at the first occurrence of the substring (separator) and
returns the string partitioned into three parts.
1. Substring before the separator
2. Separator
3. Substring after the separator
11
If the separator is not found in the string, it returns the whole string itself and two
empty strings
split()
Handling Strings
Q. Write a program with a user defined function to count the number of times
a character (passed as argument) occurs in the given string.
#Program
#Function to count the number of times a character occurs in a
def charCount(ch,st):
count = 0
for character in st:
if character == ch:
count += 1
return count
st = input(“Enter a string: “)
ch = input(“Enter the character to be searched: “)
12
count = charCount(ch,st)
print(“Number of times character”,ch,”occurs in the string is:”,count)
Output:
Enter a string: Today is a Holiday
Enter the character to be searched: a
Number of times character a occurs in the string is: 3
#Program
#Function to replace all vowels in the string with ‘*’
def replaceVowel(st):
newstr = ”
for character in st:
if character in ‘aeiouAEIOU’:
newstr += ‘*’
else:
newstr += character
return newstr
st = input(“Enter a String: “)
st1 = replaceVowel(st)
print(“The original String is:”,st)
print(“The modified String is:”,st1)
Output:
Enter a String: Hello World
The original String is: Hello World
The modified String is: H*ll* W*rld
Q. Write a program to input a string from the user and print it in the reverse
order without creating a new string.
#Program
#Program to display string in reverse order
st = input(“Enter a string: “)
for i in range(-1,-len(st)-1,-1):
print(st[i],end=”)
13
Output:
Enter a string: Hello World
dlroW olleH
#Program
#Function to reverse a string
def reverseString(st):
newstr = ” #create a new string
length = len(st)
for i in range(-1,-length-1,-1):
newstr += st[i]
return newstr
#end of function
st = input(“Enter a String: “)
st1 = reverseString(st)
print(“The original String is:”,st)
print(“The reversed String is:”,st1)
Output:
Enter a String: Hello World
The original String is: Hello World
The reversed String is: dlroW olleH
#Program
#Function to check if a string is palindrome or not
def checkPalin(st):
i=0
j = len(st) – 1
while(i <= j):
if(st[i] != st[j]):
return False
14
i += 1
j -= 1
return True
#end of function
st = input(“Enter a String: “)
result = checkPalin(st)
if result == True:
print(“The given string”,st,”is a palindrome”)
else:
print(“The given string”,st,”is not a palindrome”)
Output 1:
Enter a String: kanak
The given string kanak is a palindrome
Output 2:
Enter a String: computer
The given string computer is not a palindrome