
String Manipulation in Python |CBSE Class 11| Computer Science
Dear Class 11th STUDENTS, ! Welcome to this tutorial of String Manipulation in Python from your CBSE class 11 of Computer Science Syllabus .
In this tutorial, we shall be learning our chapter-9: String Manipulation in Python from Unit 2: Programming and Computational Thinking (PCT-1) as CBSE BOARD suggested to learn about computer system and its organisation to complete this section.
After going through this tutorial, you will be able to understand the following topics from your latest syllabus 2025-26.
Unit 2: Programming and Computational Thinking (PCT-1)
Chapter 9: String Manipulation in Python programming Language
- Introduction,
- String operations (concatenation, repetition, membership and slicing),
- Traversing a string using loops,
- Built-in functions/methods
I advice you to check the latest syllabus given by CBSE Board at its Official website: www.cbseacademic.nic.in
Also, in this tutorial we will covers all necessary topics/concepts required to complete your exams preparations in CBSE classes 11th.
NOTE:
- We are also giving some important Questions & Answers for better understanding as well as preparation for your examinations.
- You may also download PDF file of this tutorial from our SHOP for free.
- For your ease and more understanding, we are also giving the video explanation class of each and every topic individually, so that you may clear your topics and get success in your examinations.
Introduction
All of you should have basic knowledge about python strings. You know that python strings are characters enclosed in quotes of a type – single quotation marks, double quotation marks and triple quotation marks.
You have also learnt things like – an empty string is a string that has 0 characters (i.e., it is just a pair of quotation marks) and that python strings are immutable. You have used strings I earlier chapters to store text type of data. You know by now that strings are sequences of characters, where each character has a unique position-id/index.
The indexes of a string begin from 0 to length -1 ) in forward direction and -1, -2, -3, …., – length in backward direction. One of the most fundamental data types in Python is the string.
Strings are a collection of characters, and they are used to represent text data in Python. In this tutorial, we will provide an introduction to working with text data in Python, specifically focusing on strings in Python.
What is String in Python?
A Strings is a sequence of characters enclosed in single or double quotes. It can be used to represent text data, including words, sentences, and even entire documents. A string is a immutable data type, which means that once a string is created, it cannot be modified. However, you can create a new string by concatenating two or more strings.
Creating String in Python:
To create a string in Python, we simply need to enclose a sequence of characters in single or double quotes. For example:
my_string = "Hello, world!"
And, you can also use triple quotes to create a string that spans multiple lines:
my_string = """This is a multi-line string"""
Accessing Characters of a String in Python:
We can access individual characters in a string using indexing. In Python, indexing starts at 0, which means that the first character in a string has an index of 0. For example:
my_string = "Hello, world!"
print(my_string[0])
# Output: H You can also access a range of characters in a string using slicing. Slicing allows you to extract a substring from a string. For example:
my_string = "Hello, world!"
print(my_string[0:5])
# Output: Hello
Types of Strings in Python
Let’s start exploring the different types of strings in Python and their functions.
Single Line String in Python:
Single line strings are strings that are contained within a single line. They are the most commonly used type of string in Python and are created by enclosing a sequence of characters within single or double quotes.
Here’s an example of creating a single line string:
my_string = "Hello, World!"
In this case, my_string is a single line string that contains the text “Hello, World!”.
Single line strings are useful for storing short text strings such as variable names, function names, and short messages. They are also used for concatenating with other strings and for performing string operations.
Multiline String in Python:
Multiline strings are strings that span across multiple lines. They are created by enclosing a sequence of characters within triple quotes – either single or double quotes. Multiline strings are useful when you need to store long text strings that span across multiple lines, such as paragraphs, articles, or code comments.
Here’s an example of creating a multiline string:
my_string = '''Python is a powerful programming language that is used for web development, data analysis, machine learning, and artificial intelligence. It has a simple and easy-to-learn syntax and is loved by developers worldwide.'''
In this case, my_string is a multiline string that contains the text “Python is a powerful programming language that is used for web development, data analysis, machine learning, and artificial intelligence. It has a simple and easy-to-learn syntax and is loved by developers worldwide.”.
Multiline strings are useful for creating complex string structures such as formatted strings, code blocks, and documentation strings. They are also useful for storing text that needs to be formatted or indented.
ASCII Strings in Python:
The ASCII string is the most basic type of string in Python. It contains only the characters in the ASCII character set, which includes letters, numbers, and symbols commonly used in the English language. You can create an ASCII string in Python by enclosing the characters in single or double quotes.
Here’s an example:
my_string = 'Hello, World!'
In this case, my_string is an ASCII string that contains the text “Hello, World!”.
Unicode String in Python:
Unicode is a standard for encoding characters from all the world’s writing systems, including languages that use non-Latin scripts. Python supports Unicode strings, which can represent characters from any language or writing system.
You can create a Unicode string in Python by adding the prefix “u” or “U” before the quotes:
my_unicode_string = u'Hello, 世界!'
In this case, my_unicode_string is a Unicode string that contains the text “Hello, 世界!”, which means “Hello, world!” in Chinese.
Raw String in Python:
A raw string is a string that is treated as a sequence of characters without any special meaning for backslashes. This is useful for strings that contain regular expressions, file paths, or other characters that may be interpreted differently in Python.
You can create a raw string in Python by adding the prefix “r” or “R” before the quotes:
my_raw_string = r'C:\Users\Documents\file.txt'
In this case, my_raw_string is a raw string that represents the file path C:\Users\Documents\file.txt”.
Formatted String in Python:
Formatted strings are a convenient way to insert variables and expressions into a string. You can create a formatted string in Python by adding the prefix “f” or “F” before the quotes and using curly braces to enclose the variables or expressions:
name = 'Alice' age = 30
my_formatted_string = f'My name is {name} and I am {age} years old.'
In this case, my_formatted_string is a formatted string that contains the variables name and age in the text.
Byte String in Python:
Byte strings are a type of string that contains bytes instead of characters. This is useful for working with binary data, such as images, audio, or video files. You can create a byte string in Python by adding the prefix “b” or “B” before the quotes:
my_byte_string = b'\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21'
In this case, my_byte_string is a byte string that contains the hexadecimal representation of the ASCII string “Hello World!”.
Traversing a String
You know that individual character of a string is accessible through the unique index of each character. Using the indexes, you can traverse a string character by character. Traversing refers to iterating through the elements of a string, one character at a time. You have already traversed through strings, though unknowingly, when we talked about sequences along with for loop. To traverse through a string, you can write a loop like: The information that you have learnt till now is sufficient to create wonderful programs to manipulate strings. Consider the following programs that use the python string indexing to display strings in multiple ways.
String Operators
In this section, you’ll be learning to work with various operators that can be used to manipulate strings in multiple ways. We’ll be talking about basic operators + and*, membership operators in and not in and comparison operators (all relations operators ) for strings.
Basic Operators
The two basic operators of strings are: + and *. You have used these operators as arithmetic operators before for addition and multiplication respectively. But when used with strings, + operators perform concatenation rather than addition and * operator performs replication rather than multiplication. Let us see, how. Also, before we proceed, recall that strings are immutable i.e., un-modifiable. Thus, every time you perform something on a string that changes it, Python will internally create a new string rather than modifying the old string in place.
String Concatenation Operator +
The + operator creates a new string by joining the two operand strings, e.g., Consider some more examples: Expression will result into ‘1’ + ‘1’ ‘11’ ‘’a’’ + ‘’o’’ ‘ao’ ‘123’ + ‘abc’ ‘123abc’ Let us see how concatenation takes place internally. Python creates a new string in the memory by storing the individual characters of first-string operand followed by the individual characters of second-string operand. (See below)
Original strings are not modified as strings are immutable; new strings can be created but existing strings cannot be modified
Attention !
Another important thing that you need to know about + operator is that this operator can work with numbers and strings separately for addition and concatenation respectively, but in the same expression, you cannot combine numbers and strings as operands with a + operator.
For example,
2 + 3 = 5 # addition – VALID
‘2’ + ‘3’ = ‘23’ # concatenation -VALID
But the expression
‘2’ + 3
Is invalid. It will produce an error like:
>>> ‘2’ + 3
Traceback (most recent call last):
File ‘’<pyshe11#2>’’, line 1, in <module>
‘2’ + 3
TypeError : cannot concatenate ‘str’ and ‘int’ objects
Thus, we can summarize + operator as follows:
working of python + operator
String Replication Operator (*)
The * operator when used with numbers) i.e., when both operands are numbers), it performs multiplication and returns the product of the two number operands.
To use a* operator with strings, you need two types of operands- a string and a number, i.e., as number * string or string* number.
Where string operand tells the string to be replicated and number operand tells the number of times, it is to be repeated; python will create a new string that is a number of repetitions of the string operand.
For example,
Attention !
Another important thing that you need to know about + operator is that this operator can work with numbers as both operands for multiplication and with a string and a number for respectively, but in the same expression, you cannot have strings as both the operands with a * operator.
For example,
2 * 3 = 6 # multiplication – VALID
‘2’ + ‘3’ = ‘23’ # replication -VALID
But the expression
“2” * + “3”
Is invalid. It will produce an error like:
>>> “2” * “3”
Traceback (most recent call last):
File ‘’<pyshe11#0>’’, line 1, in <module>
“2” * ”3”
TypeError : can’ t multiply sequence by non- int of type “str”
Thus, we can summarize + operator as follows:
working of python * operator
Membership operator
There are two membership operators for string (in fact for all sequence types ). These are in and not in. we have talked about them in previous chapter, briefly. Let us learn about these operation in context of strings.
Recall that:
Both membership operators (when used with strings), require that both operands used with them are of string type, i.e.,
< string > in < string >
< string > in not < string >
example
“12” in “xyz”
“12” not in “xyz”
Now, let’s have a look at some example:
The in and not in operators can also work with string variables. consider this:
>>> sub = “help”
>>> string = ‘helping hand’
>>> sub2 = ‘help’
>>>sub in string
True
>>>sub2 in string
False
>>> Sub not in string
False
Sub2 not in string
True
Comparison Operators
Python’s standard comparison operators i.e., all relational operators (<, <=, >=, ==, !=) apply to strings also. The comparisons using these operators are based on the standard character-by-character comparison rules for Unicode (i.e., dictionary order).
Thus, you can make out that
Equality and non-equality in strings are easier to determine because it goes for exact character matching for individual letters including the case (upper-case or lower-case) of the letter. But for other comparisons like less than (<) or greater than (>), you should know the following piece of useful information.
As internally Python compares using Unicode values (called ordinal value), let us know about some most common characters and their ordinal values. For most common characters, the ASCII values and Unicode values are the same.
The most common characters and their ordinal values are:
Thus, upper-case letters are considered smaller than the lower-case letters. For instance,
Thus, you can say that Python compares two strings through relational operators using character-by-character comparison of their Unicode values.
String Slices
As an English term, you know the meaning of word ‘slices’, which means – ‘a part of’. in the same way, in python, the term ‘string slices refers to a part of the string, where string, where string are sliced using a range of indices.
That is, for a string say name, if we give name [ n:m] where n and m are integers and legal indices, python will return a slice of the string by returning the characters falling between indices n and m – starting at n, n+1, n+ 2…. Till m – 1. Let us understand this with the help of examples. Say we have a string namely word storing a string ‘amazing’ i.e.,
Then,
From above examples, one thing must be clear to you:
- In a string slices, the character at last index (the one following colon (:)) is not included in the result.
In a string slice, you give the slicing range in the form [<begin-index>:]. If, however, you skip either of the begin-index or last, python will consider the limits of the string i.e., for missing begin-index, it will limit of the string i.e., for begin-index, it will consider 0 (the first index) and for missing last value, it will consider length of the string.
Consider following example to understand this
The string slices refers to a part of the string s[start: end] that is the elements beginning at start the extending up to but not including end.
Following figure (fig.9.1) shows some string slices:
String Functions and Methods
There are many Python string methods available, but here are some of the most commonly used:
- .lower(): Converts all the characters in a string to lowercase.
- .upper(): This method converts all the characters in a string to uppercase.
- .replace(): Replaces a substring with another substring in a string.
- .split(): Method splits a string into a list of substrings based on a delimiter.
- .startswith(): Method checks if a string starts with a given substring.
- .endswith(): Checks if a string ends with a given substring.
- .strip(): This method removes leading and trailing whitespace characters from a string.
Python also offers many built-in functions and methods for string manipulation. You have already worked with one such method len ( ) in earlier chapters. In this chapter, you will learn about many other built-in powerful string methods of Python used string manipulation.
Every string object that you create in Python is actually an instance of string class (you need not do anything specific for this ; Python does it for you – you know built-in ). The string manipulation methods that are being discussed below can be applied to string as per following syntax:
<string Object>. <method name> ( )
In the following table we are referring to <stringObject> as string only (no angle brackets) but the meaning is intact i.e., you have to replace string with a legal string (i.e, either a string literal or a string variable that holds a string value).
Let us now have a look at some useful built-in string manipulation methods.
Python’s Built-in String Manipulation Methods
String. Capitalize ( )
Returns a copy of the string with its first Character capitalized.
Example
>>>true. capitalize ()
True
>>> i love my India. capitalize
I love my india
String. Find (sub [, start[, end]])
Returns the lowest index in the string where the substring sub is found within the slice range of star and end. Returns 1 if sub is not found
Example
>>string=it goes as – ring ringa roses
>>>sub = ringa
>>>string. find (sub)
13
>string. Find (sub, 15, 22)
-1
>>> String. Find (sub, 15, 25)
19
String . isalnum ( )
Returns True if the characters in the string are alphanumeric (alphabets or numbers) and there is at least one character, False otherwise.
>>>string = ‘’abc123’’
>>>string 2 = ‘hello’
>>>string 3 = ‘12345’
>>>string 4 = ‘ ‘
>>> string.isalnum( )
True
>>> string 2 .isalnum( )
True
>>> string 3 .isalnum( )
True
>>> string 4 .isalnum( )
False
>>
String. islower ( )
Returns True if all cased characters in the string are lowercase. There must be at least one cased character. It returns False otherwise.
Example
>>>string = ‘hello’
>>>string 2 = ‘THERE’
>>>string 3 = ‘Goldy’
>>>string. islower ( )
True
>>>string 2. Islower ( )
False
>>>string 3. Islower ( )
False
String. Is alpha ( )
Returns True if all characters in the String are alphabetic and there is at Least one character, false otherwise
Example (considering the same string values as used in example of previous function-isalnum)
>>>string .is alpha ( )
False
>>>string 2. Isalpha ( )
True
>>>string3.isalpha ( )
False
>> string4. Isalpha ( )
False
String. isspace ()
Returns True if there are only whitespace
Characters in the string. There must be at least one character. It returns False otherwise.
Example
>>>string = ‘’ ‘’ # stores three spaces
>>> string 2 = ‘’ ‘’ # an empty
>>>string. isspace ( )
True
>>> string2. Isspace ( )
False
String. isdigit ( )
Returns True if all the characters in the string are digits. There must be at least one character, otherwise it returns False
Example
(Considering the same string values as used in Example of previous function- isalnum)
>>> string.isdigit ( )
False
>>> string2.isdigit ( )
False
>>> string3.isdigit ( )
True
>>>string4. Isdigit ()
False
string. Isupper ()
Tests whether all cased characters in the string are uppercase and requires that There be at least one cased character. Returns True if so and False otherwise.
Example
>>> string = ‘HELLO’’
>>> string2 = ‘’There
>>> string3 = ‘’goldy’’
>>> string4 = ‘’U123’’ # in uppercase
>>> string5 = ‘’123f’’ # in lowercase
>>> string.isupper ( )
True
>>>string2. Isupper ( )
False
>>>string3. isupper ( )
False
>>> string4.isupper ( )
True
>>> string5.isupper ( )
False
String. lower ( )
Returns a copy of the string converted to lowercase.
Example (considering the same string values as used in example of previous function-isupper)
>>> string.lower ( )
‘hello’
>>> string2.lower ( )
‘there’
>>> string3. Lower ( )
‘goldy’
>>> string4.lower ( )
‘u123’
>>> string5.lower ( )
‘123f’
String. upper
Returns a copy of the string converted to Uppercase
Example (considering the same string values as used in example of previous function-isupper)
>>> string.upper ( )
‘Hello’
>>> string2.upper ( )
‘There’
>>> string3. upper( )
‘Goldy’
>>> string4.upper( )
‘u123’
>>> string5.upper ( )
‘123f’
Other Built-in methods that you can use on strings:
S.N | METHOD | DESCRIPTION |
1 | capitalize(): | Converts the first character to upper case |
2 | casefold() | Converts string into lower case |
3 | center() | Returns a centered string |
4 | count() | Returns the number of times a specified value occurs in a string |
5 | encode() | Returns an encoded version of the string |
6 | endswith() | Returns true if the string ends with the specified value |
7 | expandtabs() | Sets the tab size of the string |
8 | join() | Converts the elements of an iterable into a string |
9 | ljust() | Returns a left justified version of the string |
10 | lower() | Converts a string into lower case |
11 | lstrip() | Returns a left trim version of the string |
12 | maketrans() | Returns a translation table to be used in translations |
13 | partition() | Returns a tuple where the string is parted into three parts |
14 | replace() | Returns a string where a specified value is replaced with a specified value |
15 | rfind() | Searches the string for a specified value and returns the last position of where it was found |
16 | rindex() | Searches the string for a specified value and returns the last position of where it was found |
17 | rjust() | Returns a right justified version of the string |
18 | rpartition() | Returns a tuple where the string is parted into three parts |
19 | rsplit() | Splits the string at the specified separator, and returns a list |
20 | rstrip() | Returns a right trim version of the string |
21 | split() | Splits the string at the specified separator, and returns a list |
22 | splitlines() | Splits the string at line breaks and returns a list |
23 | startswith() | Returns true if the string starts with the specified value |
24 | strip() | Returns a trimmed version of the string |
25 | swapcase() | Swaps cases, lower case becomes upper case and vice versa |
26 | title() | Converts the first character of each word to upper case |
27 | translate() | Returns a translated string |
28 | isalnum() | Returns True if all characters in the string are alphanumeric |
29 | isalpha() | Returns True if all characters in the string are in the alphabet |
30 | isascii() | Returns True if all characters in the string are ascii characters |
31 | isdecimal() | Returns True if all characters in the string are decimals |
32 | isdigit() | Returns True if all characters in the string are digits |
33 | isidentifier() | Returns True if the string is an identifier |
34 | islower() | Returns True if all characters in the string are lower case |
35 | isnumeric() | Returns True if all characters in the string are numeric |
36 | isprintable() | Returns True if all characters in the string are printable |
37 | isupper() | Returns True if all characters in the string are upper case |
38 | istitle() | Returns True if the string follows the rules of a title |
39 | isspace() | Returns True if all characters in the string are whitespaces |
40 | index() | Searches the string for a specified value and returns the position of where it was found |
41 | format_map() | Formats specified values in a string |
42 | format() | Formats specified values in a string |
43 | find() | Searches the string for a specified value and returns the position of where it was found |
44 | upper() | Converts a string into upper case |
45 | zfill() | Fills the string with a specified number of 0 values at the beginning |