0% found this document useful (0 votes)
7 views24 pages

Strings in Python

The document provides a comprehensive overview of strings in Python, detailing their characteristics, creation methods, and basic operations such as concatenation, repetition, indexing, and slicing. It explains the immutability of strings, how to access individual characters, and includes examples of string manipulation techniques. Additionally, it covers the use of the len() function and various exercises to reinforce understanding of string concepts.

Uploaded by

shreyaagarwal584
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views24 pages

Strings in Python

The document provides a comprehensive overview of strings in Python, detailing their characteristics, creation methods, and basic operations such as concatenation, repetition, indexing, and slicing. It explains the immutability of strings, how to access individual characters, and includes examples of string manipulation techniques. Additionally, it covers the use of the len() function and various exercises to reinforce understanding of string concepts.

Uploaded by

shreyaagarwal584
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

​ ​STRINGS IN PYTHON

In Python, a string is a sequence of characters used to represent text. It is treated as a single


data item. A character in a string can be an alphabet, digit, whitespace, or any other symbol.
Creating a string
Strings are one of the most commonly used data types and are enclosed in either single
quotes ('...'),double quotes ("..."), triple single quotes ('''...'''), or triple double quotes
("""..."""). Triple-quoted strings (both single and double) are often used for multi-line
strings or docstrings.
single_q = 'Hello,World !' triple_sq = '''This is a
multi-line string!'''

double_q = "Hello World" triple_dq = """This is also a


multi-line string."""

Note: In most other languages like C, C++,Java, a single character within single quotes is
treated as char data type value. But in Python we do not have char data type. Hence it is
treated as string only.
Characteristics of a String-In Python, strings have the following characteristics:
Immutable: Strings in Python are immutable, meaning once created, their content cannot be
changed.We cannot change individual characters using assignment:
>>> str="COMPUTER"
>>> str[0]='C'
TypeError: 'str' object does not support item assignment
Indexing: A string is a sequence of characters, which means we can access individual
characters using indexing , where the first character is at index 0.
Word = "Hello"
print(Word[1]) # Output: e
Slicing: We can extract a portion (substring) of a string using slicing: string[start:end]
Word = "Hello, World!"
print(Word[0:5]) # Output: Hello
Concatenation: Strings can be joined using the + operator.
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # Output: Hello World
Repetition: Use the * operator to repeat a string multiple times.
Word = "Hello"
print(Word * 3) # Output: HelloHelloHello
Iterable: Strings are iterable, meaning you can loop through them character by character
using a for loop.
for char in "Python World":
print(char)
String can be created in the following ways –
By assigning a value directly to the variable:
#1​ #2 #3 #4
name='Tina' name= "Tina" name= '''Tina''' txt = """Hello, welcome to
print(name) print(name) print(name) the world of Python"""
print(txt)
1 | Page Class XI – Strings Session 2025-26
By taking input from the user:
name=input('Enter a string') #input() always return input in string form
print(name)
Using the str() Function:
Converts other data types to strings.
num = 123
str_num = str(num) # Output: '123'

Creating an Empty String


To create an empty string in Python, we can use single or double quotes, or str() builtin
function.
text=""
print(text)
>>> name='' >>> name="" >>> name=str()
>>> print('name:',name) >>> print('name:',name) >>> print('name:',name)
name: name: name:
>>> len(name) >>> len(name) >>> len(name)
0 0 0

Note : Note: The len() function returns the number of characters in a string. It returns
an integer representing the length of the given object.
Basic String Operations:
1. String Concatenation: Joining two or more strings using the Concatenation (+) operator.
str1 = "Hello"
str2 = "World"
concatenate = str1 + " " + str2 #line 3
print(concatenate) #output would be Hello World
What would be the output if we change line number 3 to concatenate = str1 + str2 ?
Note: You cannot combine numbers and strings with a + operator. ‘2’+3 -This expression is
invalid and produces a type error.
2. String Repetition: Repeating a string using the Replication (*) operator.
repeated = "Hello" * 3
print(repeated) # the output would be HelloHelloHello
Note: >>> 'teena'*'3' # cannot work if both operands are of string type
This expression is invalid and produces a type error.

What would be the output ?


>>> text='Online Learning ' s='Python'
>>> text*2 print('Fun with ' + s*3)

>>> text='Online Learning' text='Online Learning'


>>> text2=text + ' is fun' text2='is fun'
>>> print(text2) print(text+' ' + text2)

2 | Page Class XI – Strings Session 2025-26


What would be the output of the following expressions ?

>>> "abc" *2 >>> '2' * 3

>>> 5 * '"@" >>> "2" * "3"

>>> '1' + '1' >>> 'Tea'+'pot'

>>> 'a' + '0' >>> 'a'+ 0

Question: An easy way to print blank lines is print(). However, to print ten blank lines, would
you write print() 10 times ? Or is there a smart alternative? If yes, write code to print a line
with 30 ‘=’ symbol followed by 10 blank lines and one more line with 30 ‘=’ symbols.
3. Indexing: Each individual character in a string can be accessed using a technique called
indexing.
String in python has a two-way index for each location. Strings are stored by storing each
character separately in contiguous locations. The characters of the strings are given two-way
indices:
word P Y T H O N
Forward index 0 1 2 3 4 5
Backward index -6 -5 -4 -3 -2 -1
***If we give an index value out of this range then we get an IndexError. The index must be
an integer (positive, zero or negative).
Example:
text = "Hello"
first_char = text[0] # Result: 'H'
last_char = text[-1] # Result: 'o'
text="Online Learning" text="Online Learning"
print(text[0]) print(text[2])
print(text[4]) print(text[11])
print(text[6]) print(text[12])
print(text[8]) print(text[8])
text="Online Learning" text="Online Learning"
print(text[-5]) print(text[-8])
print(text[-3]) print(text[-10])
print(text[-2]) print(text[-6])
print(text[-1]) print(text[-5])
print(text[-11])

If we give an index value out of the range then we get an IndexError.


>>>text="Online Learning"
>>> text[-20] # IndexError: string index out of range
>>> text[15] # IndexError: string index out of range
>>> text[1.5] # TypeError: string indices must be integers, not 'float'

3 | Page Class XI – Strings Session 2025-26


Points to remember:
▪​ First character of the string is at index 0 or –length
▪​ Second character at index 1 or –(length-1)
▪​ Second last character at index (length-2) or -2
▪​ Last character of the string at index (length-1) or -1
▪​ The character assignment is not supported in string because strings are immutable.
​ str = “BYE”
str[1] = ‘y’ # it is invalid. Individual letter assignment not allowed in python
>>> text="Hello , Welcome to Python World."
>>> count=len(text)
>>> print(count)
33
>>> print(len(text)-1)
32
>>> print(-len(text))
-33
Note : Each character of String has an index (0 to len(String)-1) or (-1 to – len(String))
in backward. The size of the string is the total number of characters present in the string. (If
there are n characters in the string, then the last index in forward direction would be n-1 and
last index in backward direction would be –n.)
4. Slicing: String slicing in Python allows you to extract a portion of a string by specifying a
range of indices. Slicing creates a new substring from the source string and the original string
remains unchanged.
Syntax using slice operator: sequence [start : stop : step]
start: The index where the slice begins (inclusive).
stop: The index where the slice ends (exclusive, stop-1).
step: The interval between elements (optional, defaults to 1).
>>> S='Online Learning'
>>> S[1:5] # gives substring starting from index 1 to 4 'nlin'
>>> S[8:12] #gives stubstring starting from index 8 to 11 'earn'
>>> S[:8] # gives substring from index 0 to 7 'Online L'
>>> S[4:] #gives substring from index 4 to end 'ne Learning'
Note : [:] omitting both the indices directs the Python Interpreter to extract the entire string
starting from 0 till the last index.
Negative indexes can also be used for slicing. Negative indices count from the end of the
string.
>>> S[-6:-1] #characters at index -6,-5,-4,-3 and -2 are sliced 'arnin'
>>> S[-5:] #interpreter counts from the right side,start from -5 & will print all the
characters till index -1. 'rning'
>>> S[:-2] #The entire string will be printed except the last two letters.
'Online Learni'
>>> print(S[0:10:2]) #using 3 index that is step
rd
Oln e
>>> print(S[::2]) #by default step is 1 Oln erig
>>> print(S[::4]) Onei
>>> print(S[::-1]) #string is obtained in the reverse order gninraeL enilnO
4 | Page Class XI – Strings Session 2025-26
>>> print(S[::-2]) gire nlO
What would be the output of?
text = "Hello, World!"
chars = text [-9:]
print(chars)
Write the output of the following statements if word="Chocolate"
Statement​ Output
>>> word[4]​ _______________________
>>> word[-3]​ _______________________
>>> word[2:4]​ ​ ​ _______________________
>>> word[0:5]​ ​ ​ _______________________
>>> word[3:]​ ​ ​ _______________________
>>> word[-4:]​ ​ ​ _______________________
>>> word[0:6:2]​ ​ ​ _______________________
>>> word[-1:-4:-1]​​ ​ _______________________
>>> word[::2]​ ​ ​ _______________________
>>> word[::-1]​ ​ ​ _______________________
5. Length: len() is a built-in function in Python that is used to determine the length of
various data types such as strings, lists, tuples, dictionaries, and other iterable objects. It
returns an integer representing the length of the given object provided as an argument.
The general syntax for the len() function is: len(object)
Here, an object can be any iterable such as a string, list, tuple, dictionary, set, etc(that is any
sequence).
Write a program to count the number of characters in an inputted string.
text="Online Learning" Answer the following :
print(len(text)) 1.​ What is the negative index of
n=len(text) letter i in the word ‘Online’?
print('total number of characters in the string:',n)
print(text[n-1]) # last character of the string 2. Write the positive and negative
print(text[-n]) # first character of the string index of letter e in the word
‘Learning’ ?
output
3. Line 2,print(len(text)) is displaying
15 instead of 14 ? Explain why?

What will be the result of the following expressions?


a >>> "Wow Python" [1]

b >>> "Strings are fun." [5]

5 | Page Class XI – Strings Session 2025-26


c >>> len("Teapot")

d >>> "Mystery"[:4]

e >>> len('I love my country!')

f >>> 'Teapot'[3:]

What would be the output of the following code?


name="Wednesday"
L=len(name)
print(name[L-1])
print(name[-L])
print(name[L-4+1])
print(name[-L+5])
Answer the following :
For a string s storing ‘Goldy’ , what would be s[0] and
s[-1] return?

The last character of a string s is at index len(s)-1.


(State True / False)

What would be the output ?


print('One', 'Two' * 2)
print('One' + 'Two' * 2)
print(len('0123456789'))

print("""
1
2
3
""")

From the string S='Carpe Diem', which ranges will


return Die and Car ?

>>> text="Test\nNext line"


>>> print(text)

What is the index value of the last element of any


string ?

If the length of the string is 20 then what would be the


positive index of the last element of the string ?

Write the positive and negative index of letter ‘u’ in the


string “Immutable”.
word = ‘amazing’, Write the output of the following statements-
>>> print(word[3:],word[:3])
>>> print(word[:3]+word[3:])
>>> print(word[:-7],word[-7:])

6 | Page Class XI – Strings Session 2025-26


>>> print(word[:-7]+word[-7:])
>>> word[1:6:2]
>>> word[-7:-3:3]
>>> word[::-2]
>>> word[::-1]
>>> print(word[7])
>>> print(word[4:8])
>>> print(word[7:10])
Study the given code and write the answers to the questions.
s=input("Enter Some String:")
i=0
for x in s:
print("The character present at positive index ", i, "is" , x)
i=i+1
Q1. What is the output of the above program ?
Q2. What is the beginning value of the variable i ?
Q3. What is the end value of the variable i ?
#Write a program to print a - after each character
name="PYTHON"
for ch in name:
print(ch,'-',end="")
#Write a program to read a string and display in reverse order
str=input('enter a string')
length=len(str)
for a in range(-1,-length-1,-1):
print('index' , a , 'is', str[a])
#Write a program to print each character in a new line
str1="Python Program"
for i in str1:
print(i)
Write the output of the following program if the inputted text is CARD.
text=input('Enter any text')
for i in range(0, len(text)+1):
print(text[0 : i ] )
What would be the output of the following code?
str=”Python is Fun”
x=0
while x < len(str1):
print(str1[x])
x=x+1
1.​ Write a program to count the number of characters in a string without using the len()
function.
2.​ Write a program to accept a word from the user. Display each character of the inputted
word in a separate line using the ‘while’ loop?
3.​ Write a program to count the number of times a character occurs in an inputted string?
4.​ Write a program to input an integer and check if it contains 0(zero) in it.

7 | Page Class XI – Strings Session 2025-26


5.​ Write a program to reverse a string
6.​ Write a program to count the number of vowels in it.
7.​ Write a program to Check if a word is a palindrome.
8.​ What will be the output of the following program?
text = input("Enter a string: ")
for char in text:
if 'a' <= char and char <= 'z':
uchar = chr(ord(char) - 32)
print(uchar, end='')
else:
print(char, end='')
9.​ What would be the output?
for x in range(len("Tini and Mini")):
print(x)
print()
text="Tini and Mini"
for x in range(len(text)):
print(text[x],'-',x)

Use of Membership and Comparison operators in strings:


Membership Operators: Membership operators in Python, in and not in, are used to test
whether a value (or substring) is present in a sequence such as a string, list, tuple, etc. When
working with strings, these operators are particularly useful for checking the presence or
absence of substrings within a given string.
in Operator returns True if a character or substring a = "Mushroom"
exists in the string : False otherwise. print("m" in a)
>>> 'hello' in 'Hello world!' print("b" in a)
False print("shroo" in a)
// note that Python is case sensitive #output
True
False
True
not in Operator returns True if a character or substring a = "Mushroom"
does not exists in the string : False otherwise print("m" not in a)
print("b" not in a)
print("shroo" not in a)
#output
False
True
False

Note : Both membership operators when used with strings, require that both the operands
used with them should be of string type.
>>> text='Online Learning'
>>> print('L' in text) #output : True
>>> print('L' not in text) #output : False

8 | Page Class XI – Strings Session 2025-26


What would be the output of the following?

"a" in "heya" __________________


"jap" in "heya" __________________
"jap" in "japan" __________________
"jap" in "Japan" __________________
"jap" not in "Japan" __________________
"123" not in "hello" __________________
"123" not in "12345" __________________

#Checking for Substring Presence


email = "[email protected]"
if "@" in email:
print("This is a valid email address.")
else:
print("This is not a valid email address.")

#Verifying Words in a Sentence


sentence = "The quick brown fox jumps over the lazy dog."
word = "fox"
if word in sentence:
print(f"The word '{word}' is in the sentence.")
else:
print(f"The word '{word}' is not in the sentence.")
Note : f-strings are the most convenient way to format strings.
What would be the output?
text = "Hello, World!"
result = "world" in text
print(result)
Comparison Operators: Python string comparison is performed using the characters in both
strings. The characters in both strings are compared one by one. When different characters
are found then their Unicode value is compared. The character with lower Unicode value is
considered to be smaller.

fruit1 = 'Apple' o/p


print(fruit1 == 'Apple') True
print(fruit1 != 'Apple') False
print(fruit1 < 'Apple') False
print(fruit1 > 'Apple') False
print(fruit1 <= 'Apple') True
print(fruit1 >= 'Apple') True
print('apple' == 'Apple') False
print('apple' > 'Apple') True
print('A unicode is', ord('A'), ',a unicode is', ord('a')) A unicode is 65 ,a unicode is 97

9 | Page Class XI – Strings Session 2025-26


So “Apple” is smaller when compared to
“apple” because of their Unicode
values(called ordinal value).
print('Apple' < 'ApplePie') True
#If the characters sequence are the
same in both the strings but one of them
has some additional characters, then the
larger length string is considered greater
than the other one.
print('apple' < 'apple') False
print('apple' > 'apple') False
# both the strings are neither smaller nor
greater than the other one. Hence the
output is false in both the cases.

Write the output of the following code snippet?


str1 = "apple"
str2 = "banana"
result = str1 < str2
print(result)

str1 = "Apple"
str2 = "apple"
result = str1 == str2
print(result)
result = str1 < str2
print(result)

What is this program doing ?


str="Custard Apple"
ctr=0
for ch in str:
if ch in "aeiouAEIOU":
ctr += 1
print(ctr)

Answer the following questions:


1.​ Is there any difference between 1 and ‘1’ in Python ?
2.​ Is there any difference between ‘a’ and “a” in Python ?
3.​ What will be the output of print(‘Ria’*7+’GoodBye’) ?
4.​ Index value can be a floating point number in Python ?
5.​ Assign a string Slicing to a string variable named text?
6.​ Write the output of the following Python statements:
>>> print('x' in "Avengers")
>>> print('g' in "Avengers")
>>> print('v' not in "Avengers")
>>> print('b' not in "Avengers")

10 | Page Class XI – Strings Session 2025-26


7.​ Write the output of the following code.
S="FUN"
for i in S:
print(i,end=' ')
print()
for j in S:
print(j,end='*')
print()
for k in S:
print(k*2)
8.​ Output of the following code:
S="FUN"
for i in range(2,7,2):
print(i*S)

Match the output of the following program with your findings:(Output has been given
as a comment in each print statement)
# Define sample strings
str1 = "Hello"
str2 = "World"
str3 = "hello"
str4 = "apple"
str5 = "banana"
# Equality and inequality
print(str1 == str2) # False
print(str1 == "Hello") # True
print(str1 != str2) # True
print(str1 != "Hello") # False
# Lexicographical comparison
print(str4 < str5) # True ('apple' < 'banana')
print(str5 > str4) # True ('banana' > 'apple')
print(str4 <= "apple") # True
print(str5 >= "banana") # True
# Case-sensitive comparison
print(str1 == str3) # False
print(str1 < str3) # True ('H' < 'h' in Unicode)
print(sorted_fruits)

Traversing a String
Traversing a string in Python involves iterating over each character in the string, one at a time.
This can be done using various methods, such as loops (for loop, while loop) or
comprehensions.
Using a for Loop
The most straightforward way to traverse a string is by using a for loop. This allows you to
access each character directly.

11 | Page Class XI – Strings Session 2025-26


S='Online Learning'
for str in S:
print(str) #each character will be printed
Using a while Loop
You can also use a while loop to traverse a string by indexing each character.
S='Online Learning'
index = 0
while index < len(S):
print(S[index])
index += 1
Using String Indexing
String indexing can be used to access characters at specific positions.
text = "Hello, World!"
for i in range(len(text)):
print(text[i])

Traversing with String Slicing


You can use slicing to traverse parts of a string.
text = "Hello, World!"
for i in range(len(text)):
print(text[i:i+1])

#example
name="PYTHON"
for ch in name:
print(ch,'-',end="") # Output : P -Y -T -H -O -N -

#Example to read a string and display in reverse order


str=input('enter a string: ')
length=len(str)
for a in range(-1,-length-1,-1):
print('index',a,'is',str[a])
Output
enter a string: python
index -1 is n
index -2 is o
index -3 is h
index -4 is t
index -5 is y
index -6 is p
Modify the above #Example to read a string and display in reverse order and check the
difference in outputs
i.​ for a in range(-1,-length,-1):#change for st. and check the o/p
ii.​ print(a,end="") #change print st. and check the

12 | Page Class XI – Strings Session 2025-26


Write a program to take input for a string. Display the string in the following
format
F
U
N
and also display the length of the string.
How to dry run a program ?
str=input('enter a string')
print ('the string before traversal :',str)
length=len(str)
i=0
for a in range(-1,-length-1,-1):
print(str[i],"\t", str[a])
i+=1

Note: A dry run of a Python program involves manually simulating the program's execution
step by step, without actually running the code on a computer. This helps in understanding the
flow of the program, identifying logical errors, and predicting its behaviour.
length = len(str) evaluates to length = 5
i=0
for a in range(-1, -length-1, -1):
range(-1, -6, -1) generates the sequence: -1, -2, -3, -4, -5

String Methods and Built-In Functions


Syntax: <stringobject> . <method name>()
Method Description with example
capitalize() Returns a copy of the string with its first character capitalized (if it is an
alphabet) that is Only first character will be converted to upper case and all
remaining characters can be converted to lowercase.
>>> 'india'.capitalize()
'India'

13 | Page Class XI – Strings Session 2025-26


>>>str1="hello WORLD"
'Hello world'
title() Returns the string with the first letter of every word in the string in
uppercase and rest in lowercase.
>>> str1="hello WORLD"
>>> str1.title()
'Hello World'
Write a Python script to accept a sentence from the user. Check and
change the first letter of each word to title case.
lower() Returns the string with all uppercase letters converted to lowercase
>>> str1='Hello World'
>>> str1.lower()
'hello world'
Write a Python script that accepts a string from the user and converts
all uppercase alphabets to lowercase while keeping the rest of the
characters (lowercase alphabets and others) unchanged.
upper() Returns the string with all lowercase letters converted to uppercase.
>>> str1="hello WORLD"
>>> str1.upper()
'HELLO WORLD'
#use of upper() and lower()
sent = input("Enter a sentence: ")
Upper = sent.upper()
print("Upper case sentence:",Upper)
Lower = sent.lower()
print("Lower case sentence:",Lower)
Write a Python script that accepts a string from the user and converts
all lowercase alphabets to uppercase while keeping the rest of the
characters (uppercase alphabets and others) unchanged.
count We can find the number of occurrences of substring present in the given string
(str, start, end) by using the count() method.
1. s.count(str) - It will search throughout the string.
2. s.count(str, start, end) - It will search from start index to end-1 index.
s="Aabra Ka Daabra"
print(s.count('a'))
print(s.count('ab'))
print(s.count('a',3,7))
o/p
6
2
1
find find() returns the index number of the first occurrence of the given search
(str,start, end) substring in the specified string (that is returns the lowest index in the string
where the substring is found).
Returns -1 if sub is not found.(sub…substring)
>>> str="it goes as - ringa ringa roses"
>>> sub="ringa"
>>> str.find(sub) #output 13
>>> str.find(sub,15,25) #output 19
>>> str.find(sub,15,22) #output -1
14 | Page Class XI – Strings Session 2025-26
str1 = "this is string example....wow!!!"
str2 = "exam";
print (str1.find(str2)) #output 15
index index() method determines if the string str occurs in string or in a substring of
(str,start,end) string, if the starting index beginning and ending index end are given. This
method is the same as find(), but raises an exception if sub is not found.
str1 = "this is a string example....wow!!!"
str2 = "exam";
print (str1.index(str2))
print (str1.index(str2, 10))
print (str1.index(str2, 10,13))
output
15
15
ValueError: substring not found
endswith() Returns True if the given string ends with the supplied substring otherwise
returns False.
>>> str1='Hello World!'
>>> str1.endswith('World!') #output True
>>> str1.endswith('!') #output True
>>> str1.endswith('World') #output False
startswith() Returns True if the given string starts with the supplied substring otherwise
returns False.
>>> str1='Hello World!'
>>> str1.startswith('He') #output True
>>> str1.startswith('Hee') #output 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.
>>> str1='Hello World!'
>>> str1.isalnum() #output would be False
>>> str1='HelloWorld'
>>> str1.isalnum() #output would be True
>>> str1='HelloWorld10'
>>> str1.isalnum() #output would be True
isalpha() returns true if all the characters in the string are alphabetic and there is at
least one character, false otherwise.
>>> str1='Hello'
>>> str1.isalpha() #output True
>>> str1='Hello1'
>>> str1.isalpha() #output False
>>> str1='Hello World'
>>> str1.isalpha() #output False
>>> str1='A 123'
>>> str1.isalpha() #output False
name="Hello, Python"
if name.isalnum()==True:
print('Alphanumeric')
else:
print('Not Alphanumeric')
15 | Page Class XI – Strings Session 2025-26
isdigit() Returns True if the string contains only digits.
>>> str1='A 123'
>>> str1.isdigit() #output False
>>> str1='123'
>>> str1.isdigit() #output True
Write a Python script that accepts a string from the user and counts the
total number of digits present in that string?
islower() Returns True if the string is non-empty and has all lowercase alphabets, or has
at least one character as lowercase alphabet and the rest are non-alphabet
characters.
>>> str1='hello world'
>>> str1.islower() #output True
>>> str1='hello 123'
>>> str1.islower() #output True
>>> str1='123'
>>> str1.islower() #output False
>>> str1='Hello'
>>> str1.islower() #output False
Write a program to take input for a string. Check and display the total
number of lowercase alphabets given in the string.
isupper() Returns True if the string is non-empty and has all uppercase alphabets, or has
at least one character as uppercase character and the rest are non-alphabet
characters.
>>> str1='HELLO WORLD!'
>>> str1.isupper() #output True
>>> str1='HELLO 123'
>>> str1.isupper() #output True
>>> str1='1234'
>>> str1.isupper() #output False
>>> str1='Hello World'
>>> str1.isupper() #output False
Write a program to take input for a string. Check and display the total
number of uppercase alphabets given in the string.
isspace() Returns true if the string contains only spaces otherwise false.
>>> str1=' '
>>> str1.isspace() #output True
>>> str1='1 2'
>>> str1.isspace() #output False
>>> str1='\n \t'
>>> str1.isspace() #output True
Write a program to take input for a string. Check and display the total
number of spaces used in the string.
istitle() If the first letter of each word in the string are uppercase, this function returns
true otherwise false.
>>> str1='Hello World'
>>> str1.istitle() #output True
>>> str1='Hello world'
>>> str1.istitle() #output False
>>> str1='HELLO WORLD'
>>> str1.istitle() #output False

16 | Page Class XI – Strings Session 2025-26


lstrip() / Returns the string after removing any leading characters from the left side of
lstrip(chars) the string. (space is the default leading character to remove).
>>> str1=' Hello world'
>>> str1.lstrip() #output 'Hello world'
>>> str1='Hello world'
>>> str1.lstrip('Hello') #output ' world'
rstrip() / Returns the string after removing any trailing characters from the right side of
rstrip(chars) the string (characters at the end a string) (space is the default trailing
character to remove).
>>> str1=' Hello world'
>>> str1.rstrip() #output ' Hello world'
>>> str1=' Hello world '
>>> str1.rstrip() #output ' Hello world'
>>> str1=' Hello world'
>>> str1.rstrip('rld') #output ' Hello wo'
strip() Returns the string after removing the characters both on the left and the right
of the string (space is the default leading and trailing character to remove).
>>> str1=' Hello world '
>>> str1.strip() #output 'Hello world'
>>> str1='Domino WorlD'
>>> str1.strip('D') #output 'omino Worl'
>>> str1='Domino World'
>>> str1.strip('D') #output 'omino World'
replace(old Replace all occurrences of the old string with the new string.
string, new >>> str1='Hello World'
string) >>> str1.replace('o','*') #output 'Hell* W*rld'
>>> str1='Hello World! Hello'
>>> str1.replace('Hello','Bye') #output 'Bye World! Bye'
swapcase() returns a string where all the upper case letters are lower case and vice versa.
>>> str1='Hello World'
>>> str1.swapcase() #output 'hELLO wORLD'
Write a Python script that accepts a string from the user and converts
it to toggle case, where each uppercase letter is converted to
lowercase and each lowercase letter is converted to uppercase.
join(sequence) This method takes all items in an iterable format and joins them into one string
using a specified character.
>>> str1='Hello World'
>>> str2='-' #separator
>>> str2.join(str1) #output 'H-e-l-l-o- -W-o-r-l-d'
>>> str1='HelloWorld'
>>> str2='*' #separator
>>> str2.join(str1) #output 'H*e*l*l*o*W*o*r*l*d'
partition(separ Partitions the given string at the first occurrence of the substring (separator)
ator) and returns the string partitioned into three parts.
1. Substring before the separator
2. Separator
3. Substring after the separator
If the separator is not found in the string, it returns the whole string itself and
two empty strings.
>>> str1='India is a Great Country'
17 | Page Class XI – Strings Session 2025-26
>>> str1.partition('is')
('India ', 'is', ' a Great Country')
>>> str1.partition('are')
('India is a Great Country', '', '')
split() Returns a list of words delimited by the specified substring. If no delimiter is
given, then words are separated by space.
>>> str1='India is a Great Country'
>>> str1.split()
['India', 'is', 'a', 'Great', 'Country']
>>> str1='India is a Great Country'
>>> str1.split('a')
['Indi', ' is ', ' Gre', 't Country']
str() Converts values to a string form so they can be combined with other strings.
>>> x=5
>>> type(x)
<class 'int'>
>>> y=str(x)
>>> type(y)
<class 'str'>

1.​ Write a function count()to take input for a string. Check and print the total number of
lowercase alphabets present in the string.
2.​ Write a function count()to take input for a string. Check and print the total number of
uppercase alphabets present in the string.
3.​ Write a Python script that accepts a string from the user and converts it to toggle case,
where each uppercase letter is converted to lowercase and each lowercase letter is
converted to uppercase without using swapcase().
4.​ Complete the following program to count the number of consonants in the given string.
text = "Hello World"
vowels = "aeiouAEIOU"
count = _______
for char in ________:
if _____________ and char not in vowels:
____________
print("Number of consonants:", _________)

Handling Strings
txt = " Mango "
x = txt.strip()
print("Of all fruits",x, "is my favorite")
print( "hello World".upper().lower() )
print( "hello World".lower().upper().title() )
txt = "apple#banana#cherry#orange"
x = txt.split("#")
print(x)
s='Python is an Easy language'
print('original string >> ',s)

18 | Page Class XI – Strings Session 2025-26


print('upper>> ',s.upper())
print('lower> ',s.lower())
print('swapcase>> ',s.swapcase())
print('title case>>',s.title())
print('Sentence case>>',s.capitalize())
l=['hyderabad','singapore','london','dubai']
s=':'.join(l)
print(s)
s="abcabcabcabcabcabcab"
s1=s.replace("a","A")
print(s1)
txt="I enjoy working in Python"
x=txt.partition("working")
print(x)
print("***".join("Fun"))
print('you and I work for you'.replace('you','u'))

x="COMPUTER SCIENCE"
print(x.title())
print(x.capitalize())
print(x.startswith('CE'))

Write a program with a user defined function character() to check whether the entered
character is uppercase/lowercase letter.
#check character is Lowercase or Uppercase (method1)
def character():
ch = input("Enter a Character : ")
if(ch >= 'A' and ch <= 'Z'):
print("The Given Character ", ch, "is an Uppercase Alphabet")
elif(ch >= 'a' and ch <= 'z'):
print("The Given Character ", ch, "is a Lowercase Alphabet")
else:
print("The Given Character ", ch, "is Not a Lower or Uppercase Alphabet")
character()

#check character is Lowercase or Uppercase (method 2)


def character():
ch = input("Enter a Character : ")
if(ch.isupper()):
print("The Given Character ", ch, "is an Uppercase Alphabet")
elif(ch.islower()):
print("The Given Character ", ch, "is a Lowercase Alphabet")
else:
print("The Given Character ", ch, "is Not a Lower or Uppercase Alphabet")
character()

19 | Page Class XI – Strings Session 2025-26


#check character is Lowercase or Uppercase (method 3)
def character():
ch1 = input("Enter a Character : ")
ch=ord(ch1)
if(ch >= 65 and ch <= 90):
print("The Given Character ", chr(ch), "is an Uppercase Alphabet")
elif(ch >= 97 and ch <= 122):
print("The Given Character ", chr(ch), "is a Lowercase Alphabet")
else:
print("The Given Character ", chr(ch), "is Not a Lower or Uppercase Alphabet")
character()
Write a program with a user defined function check() whether the entered character is an
alphabet or not . If it is an alphabet then the program should display whether it is
uppercase or lowercase alphabet.
#entered character is alphabet or not
#if it is alphabet, display whether it is upper/lowercase
def check():
ch = input("Enter any character : ")
if ch.isalpha():
if ch.isupper() :
print( ch, "is UPPERCASE alphabet")
else:
print( ch, "is LOWERCASE alphabet")
else :
print(ch, "is not an alphabet.")
check()
Write a program to check whether the entered character is in the alphabet or not. If it is
alphabet then display whether it is a vowel or a consonant.
#entered character is alphabet or not.
#if alphabet , then is it a vowel or consonant
ch = input("Enter an alphabet : ")
if ch.isalpha():
if ch.lower() in "aeiouAEIOU":
print(ch, "is a vowel.")
else :
print(ch, "is a consonant.")
else:
print(ch, "is not an alphabet.")
Write a Program to check the first character of a name is alphabet or not
ch = input("Enter a string ")
if ch[0].isalpha() :
print(ch[0], "is an ALPHABET.")
elif ch[0].isdigit() :

20 | Page Class XI – Strings Session 2025-26


print(ch[0], "is a DIGIT.")
else :
print(ch[0], "is a SPECIAL CHARACTER.")
Write a program with a user defined function which replaces all vowels in the string with
'*'.
def replaceVowel():
text = input("Enter a String: ")
newtext = '' #create an empty string
for ch in text:
#check if next character is a vowel
if ch in 'aeiouAEIOU':
newtext += '*' #Replace vowel with *
else:
newtext += ch
print("The original String is:",text)
print("The modified String is:",newtext)
replaceVowel()
Write a function deleteChar() which takes two parameters one is a string and other is a
character. The function should create a new string after deleting all occurrences of the
character from the string and display the new string.
def deleteChar():
userInput = input("Enter any string: ")
delete = input("Input the character to delete from the string: ")
newstr = userInput.replace(delete,'')
print("The new string after deleting all occurrences of",delete,"is: ",newstr)
deleteChar()
Write a program using a user defined function to check if a string is a palindrome or not.
(A string is called a palindrome if it reads the same backwards as forward. For example,
Afifa is a palindrome.)
def reverseString():
st = input("Enter a String: ")
newstr = '' #create a new string
length = len(st)
for i in range(-1,-length-1,-1):
newstr += st[i]
print("The reversed String is:",newstr)
if newstr.lower()==st.lower():
print(st,'is a palindrome')
else:
print(st,'is not a palindrome')
reverseString()
Write a program to count the total number of words in a string.
#total number of words in a string
str1 = input("Enter any String : ")
wtotal = 0

21 | Page Class XI – Strings Session 2025-26


#method 1
for i in range(len(str1)):
if str1[i] == ' ':
wtotal = wtotal + 1
print("Total Number of Words in this String = ", wtotal+1)
#method 2
sp=str1.split()
length=len(sp)
print("Total Number of Words in this String = ", length)
#method 3
sp1=0
for i in str1:
if(i.isspace()):
sp1=sp1+1
print('total number of words in this String = ',sp1+1)
What would be the output of the following programs:
What is the following program doing ?Also write the output of the program.

#program 1 #program 3
str="We are learning Python" ch = input("Enter any Character: ")
str2="" if(ch.isdigit()):
strlen=len(str) print("Character", ch, "is a Digit")
for i in range(strlen): elif(ch.isalpha()):
if str[i] not in "aeiouAEIOU": print("Character", ch, "is an Alphabet")
str2=str2+str[i] else:
print("Original Text : ",str) print("Character", ch, "is a Special Character")
print("Modified Text : ",str2)

#program 2 #program 4
str="Wow Python" # Printing Alphabets
print(len(str)) print("Alphabets from a - z are : ")
print(str[0],str[-1]) # a = 97 and z = 122
for al in range(97, 123):
print(chr(al), end=" ")

#program 5
str = "The quick BROWN fox"
count = 0
vowel = "aeiouAEIOU"
for alphabet in str:
if alphabet in vowel:
x=str.swapcase()
count = count + 1
print(str)
print(x)
print("vowels :", count)

22 | Page Class XI – Strings Session 2025-26


Consider the following string: mySubject = "Computer Science"
What will be the output of the following string operations :
i. print(mySubject[0:len(mySubject)]) ii. print(mySubject[-7:-1])
iii. print(mySubject[::2]) iv. print(mySubject[len(mySubject)-1])
v. print(2*mySubject) vi. print(mySubject[::-2])
vii. print(mySubject[:3] + mySubject[3:]) viii. print(mySubject.swapcase())
ix. print(mySubject.startswith('Comp')) x. print(mySubject.isalpha())
Consider the following string: myAddress = "WZ-1,New Ganga Nagar,New Delhi"
What will be the output of following string operations :
i. print(myAddress.lower()) ii. print(myAddress.upper())
iii. print(myAddress.count('New')) iv. print(myAddress.find('New'))
v. print(myAddress.rfind('New')) vi. print(myAddress.split(','))
vii. print(myAddress.split(' ')) viii. print(myAddress.replace('New','Old'))
ix. print(myAddress.partition(',')) x. print(myAddress.index('Agra'))
Answer the following:
1.​ Write a program to input line(s) of text from the user until enter is pressed. Count the
total number of characters in the text (including white spaces),total number of
alphabets, total number of digits, total number of special symbols and total number of
words in the given text. (Assume that each word is separated by one space).
2.​ Input a string having some digits. Write a function to find the sum of digits present in
this string.
3.​ Write a function that takes a sentence as an input where each word in the sentence is
separated by a space. The function should replace each space with an underscore and
then display the modified sentence.
4.​ Write a program input a string and display the length of the string : with len function
and without len function.
5.​ Write a program to input a string and a character. Count the occurrences of that
character in the string.
6.​ Write a program to take input for a string and display the total number of consonants
present in the string.
7.​ Write a function count_details() which takes input for a string. Check and display the
following details :
Length of the string
Total number of alphabets
Total number of vowels and consonants
8.​ Write a program to reverse an inputted string.
9.​ Write a program to count the occurrences of a substring.
10.​Write a python program to input a line of text and create a new line of text where each
word of the input line is reversed?

23 | Page Class XI – Strings Session 2025-26


String Formatting: String formatting allows you to create formatted strings using different
methods:
Sometimes we would like to format our output to make it look attractive. This can be done by
using the str.format() method. This method is visible to any string object.
>>> x = 5; y = 10
>>> print(‘The value of x is {} and y is {}’.format(x,y))
The value of x is 5 and y is 10
Here the curly braces {} are used as placeholders. We can specify the order in which it is
printed by using numbers (tuple index).
>>> print('I love {1} and {0}'.format('bread','butter'))
I love butter and bread
>>> print('I love {0} and {1}'.format('bread','butter'))
I love bread and butter
We can even use keyword arguments to format the string.
>>> print(‘Hello {name}, {greeting}’.format(greeting = ‘Good morning’,name = ‘Amit’))
Hello Amit, Good morning
More programs for Practice:
1.​ Write a program that inputs a line of text and prints its each word in a separate line.
Also, print the count of words in the line.
2.​ Write a program to input a string and print each individual word of it along with its
length.
3.​ Write a program to input a string. Print the number of uppercase and lowercase letters
in it.
4.​ Write a program that asks the user for a string s and a character c, and then it prints
out the location of each character c in the string s.
5.​ Write a program to input a line of text . Print the count of vowels in it.
6.​ Write a program that reads a string and checks whether it is a palindrome string or not.
7.​ Write a program to convert lowercase alphabet into uppercase and vice versa.
***********

24 | Page Class XI – Strings Session 2025-26

You might also like