Strings and String Manipulation
Chapter 8 · Tamil Nadu State Board
- 10 min read
- 4-question quiz
Every key point below shows the sentence from your textbook it comes from. Book back answers are solved and checked against the book; answers we could not prove are left out. How we check content
In short
This lesson teaches how Python strings store and process sequences of characters. It explains string immutability, indexing, slicing, operators, formatting, and useful built-in functions. These tools help students inspect, combine, format, and search text in Python programs. The lesson also shows how strings can be used to solve practical problems such as checking palindromes and counting vowels.
Written by AI from this lesson. How we check it
Key points
- A Python string is a sequence of Unicode characters enclosed in quotes, and it cannot be changed after it is defined.
From your textbook
“String is a sequence of Unicode characters that may be a combination of letters, numbers, or special symbols”
- Triple quotes can contain strings that include different kinds of quotes and can also create multiline strings.
From your textbook
“Defining strings within triple quotes also allows creation of multiline strings.”
- Each character has a subscript: positive subscripts start at zero, while negative subscripts start at -1 from the end.
From your textbook
“The positive subscript 0 is assigned to the first character and n-1 to the last character”
- A string cannot have one character changed or deleted, but its variable can be assigned a new string or removed with del.
From your textbook
“strings in python are immutable. That means, once you define a string modifications or deletion is not allowed.”
- Python uses + to join strings, += to append, and * to repeat a string.
From your textbook
“The plus (+) operator is used to concatenate strings in python.”
- Slicing selects part of a string; its end position is excluded, and a third value can set the stride.
From your textbook
“Python takes the end value less than one from the actual index specified.”
- String membership operators check whether one string is present inside another.
From your textbook
“The ‘in’ and ‘not in’ operators can be used with strings to determine whether a string is present in another string.”
Python Strings and Creating Strings
Definition
- String
- A string is a sequence of Unicode characters, such as letters, numbers, or special symbols, enclosed in quotes.
Python strings can use single, double, or triple quotes. Use a different quote style when the string itself contains a quote mark. Triple quotes can also enclose multiline strings. Strings are immutable, so their characters cannot be changed after the string is defined.
Choosing quotes for strings
| String contents | Suitable quotes |
|---|---|
| A string without quote marks inside | Single or double quotes |
| A string containing single quotes | Double quotes |
| A string containing double quotes | Triple quotes |
| A multiline string | Triple quotes |
String Indexing and Slicing
Each character has an index, also called a subscript. Positive indexing starts at 0 for the first character and ends at n-1. Negative indexing starts at -1 for the last character and counts backwards.
Positive and negative subscripts for SCHOOL
| Character | S | C | H | O | O | L |
|---|---|---|---|---|---|---|
| Positive subscript | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative subscript | -6 | -5 | -4 | -3 | -2 | -1 |
Definition
- String slicing
- String slicing uses the [ ] operator and index values to take a character or substring from a string.
The general slice format is str[start:end]. Python stops before the end index, so the last included character is at end-1. You can leave out the start or end value. A third value, called stride, sets how many characters to move forward between selected characters; its default is 1. A negative stride reads in reverse order.
Slicing examples with THIRUKKURAL
- str1[0] gives T.
- str1[0:5] gives THIRU.
- str1[:5] also gives THIRU.
- str1[6:] gives KURAL.
Worked example
What do these slices produce from str1 = "Welcome to learn Python"?
Try it first, then show the solutionSolution
- str1[10:16] selects the characters from index 10 up to, but not including, index 16.
- str1[10:16:4] uses a stride of 4.
- str1[10:16:2] uses a stride of 2.
- str1[::3] selects characters using a stride of 3.
Answer: The results are learn, r, er, and Wceoenyo, respectively.
Remember: The end value in a slice is not included.
Changing and Deleting Strings
Because strings are immutable, Python does not allow changing or deleting one character in a string. You can assign a completely new string to the same variable, replacing its previous value. The replace() function returns a changed string, but it does not alter the original string.
replace("char1", "char2")
Replaces every occurrence of char1 with char2 in the returned string.
What string changes are allowed
- str1[0] = "A" is not allowed because a character cannot be assigned inside a string.
- del str1[2] is not allowed because an individual character cannot be deleted.
- Assigning a new string to str1 replaces its previous value.
- del str1 removes the entire string variable.
Worked example
What does print(str1.replace("o", "e")) display when str1 = "How are you"?
Try it first, then show the solutionSolution
- replace() changes each occurrence of o to e in its returned string.
- The original value of str1 is not changed.
Answer: Hew are yeu
String Operators
Operators for string operations
| Operation | How it works |
|---|---|
| Concatenation (+) | Joins two or more strings. |
| Append (+=) | Adds a string to the end of an existing string. |
| Repeating (*) | Displays a string multiple times. |
Worked example
What are the results of the string operator examples?
Try it first, then show the solutionSolution
- "welcome" + "Python" joins the two strings.
- str1 = "Welcome to "; str1 += "Learn Python" adds the new string at the end.
- str1 = "Welcome "; print(str1*4) repeats the string four times.
Answer: The results are welcomePython, Welcome to Learn Python, and Welcome Welcome Welcome Welcome.
String Formatting with % and format()
The % operator builds a string by replacing format markers with values from variables. The format() function uses curly braces { } as places for values. Both methods can insert values into a string.
Common formatting characters
- %c: character
- %d or %i: signed decimal integer
- %s: string
- %u: unsigned decimal integer
- %o: octal integer
- %x or %X: hexadecimal integer
- %e or %E: exponential notation
- %f: floating point number
- %g or %G: short number in floating point or exponential notation
Worked example
Display a name and mark using the % operator.
Try it first, then show the solutionSolution
- Set name = "Rajarajan" and mark = 98.
- Use %s for the name and %d for the mark.
- Replace the markers with the values using %(name,mark).
Answer: Name: Rajarajan and Marks: 98
Worked example
Add two input numbers and display the sum using format().
Try it first, then show the solutionSolution
- Enter 34 for Number 1 and 54 for Number 2.
- Place the values and their sum into the three curly-brace fields.
Answer: The sum of 34 and 54 is 88
Remember: In format(), curly braces { } are replacement fields. With %, use a matching formatting character for each value.
Escape Sequences in Strings
Definition
- Escape sequence
- An escape sequence starts with a backslash and can be interpreted differently from ordinary characters.
A backslash lets a string include quote characters that would otherwise mark the end of the string. Triple quotes can also display a string containing quotes. For example, these forms can display: They said, "What's there?"
Escape sequences supported by Python
- \newline: backslash and newline ignored
- \\: backslash
- \': single quote
- \": double quote
- \a: ASCII Bell
- \b: ASCII Backspace
- \f: ASCII Form feed
- \n: ASCII Linefeed
- \r: ASCII Carriage Return
- \t: ASCII Horizontal Tab
Built-in String Functions
Functions that inspect or search strings
- len(str): returns the number of characters. len("Corporation") gives 11.
- find(sub[, start[, end]]): returns the index of the first matching substring, or -1 if it is not found. The start and end values are optional.
- count(str, beg, end): counts matching substrings in the given range. The range values are optional, and the search is case sensitive.
- isalnum(): returns True if the string contains only letters and digits; otherwise it returns False.
- isalpha(): returns True if the string contains only letters.
- isdigit(): returns True if the string contains only numbers.
- islower(): returns True if the string is in lowercase.
- isupper(): returns True if the string is in uppercase.
Functions that change or display strings
- capitalize(): returns a string with its first character capitalized.
- center(width, fillchar): centers the string in the given width and fills unused columns with fillchar.
- lower(): returns a copy with all letters in lowercase.
- upper(): returns a copy with all letters in uppercase.
- title(): returns a string in title case.
- swapcase(): changes each character to the opposite case.
- ord(char): returns the ASCII code of a character.
- chr(ASCII): returns the character represented by an ASCII code.
Worked example
Find the substring 'ma' in 'mammals'.
Try it first, then show the solutionSolution
- find('ma') starts searching from the beginning and returns 0.
- find('ma',2) starts at index 2 and returns 3.
- find('ma',2,4) searches within that range and returns -1.
Answer: The substring starts at index 0 in the first search. The search from index 2 finds it at index 3.
Worked example
Change the case of "tAmiL NaDu" using swapcase().
Try it first, then show the solutionSolution
- Each lowercase letter becomes uppercase.
- Each uppercase letter becomes lowercase.
Answer: TaMIl nAdU
Remember: find() gives -1 when the substring is not found. String searches with count() are case sensitive.
Membership Operators and String Programs
Definition
- Membership operators
- The in and not in operators check whether one string is present in another string.
Worked example
Check whether "chennai" is present in the entered string.
Try it first, then show the solutionSolution
- If the entered string is "Chennai G HSS, Saidapet", the program displays Found.
- If the entered string is "Govt G HSS, Ashok Nagar", the program displays Not Found.
Answer: The result depends on whether the searched string "chennai" is present.
What the string programs do
- A palindrome program reverses the entered string and compares it with the original. malayalam is a palindrome; welcome is not.
- A pattern program prints a string made from stars in a while loop.
- A vowel and consonant program checks each character. It counts vowels from aAeEiIoOuU and counts other alphabetic characters as consonants.
- An Abecedarian series program joins each letter in ABCDEFGH with ate, giving Aate, Bate, Cate, Date, Eate, Fate, Gate, Hate.
- A vowel-removal program builds a new string without the vowels aAeEiIoOuU.
- A character-counting program checks each character and counts matches.
Worked example
Count the occurrences of e in "Software Engineering".
Try it first, then show the solutionSolution
- Check each character in the string.
- Increase the count whenever a character matches e.
Answer: The character e occurs 3 times.
Remember: Strings are immutable, so they cannot be changed during execution. A string can also be written within triple quotes to create a multiline string.
String operators in Python
The + operator joins strings; this is called concatenation. The * operator repeats a string. The in and not in operators check whether one string is present inside another string.
Worked example
What is printed by str1 = “School” and print(str1*3)?
Try it first, then show the solutionSolution
- The * operator repeats the string three times.
Answer: SchoolSchoolSchool
The in operator checks for the presence of a string. The not in operator checks that it is absent.
String indexing and slicing
Definition
- Slicing
- Slicing selects part of a string using the slicing operator [ ].
A string subscript, or index, may be positive or negative. A slice operation can use a stride, which is its third argument. The code str1[::-1] reverses the string.
Worked example
What does str1 = "welcome"; str2 = "to school"; str3 = str1[:2]+str2[len(str2)-2:]; print(str3) display?
Try it first, then show the solutionSolution
- str1[:2] selects the first two characters: we.
- str2[len(str2)-2:] selects the last two characters: ol.
- The + operator joins the selected parts.
Answer: weol
String properties and formatting
Definition
- Immutable string
- An immutable string cannot be changed by assigning a new character to one of its positions.
Triple quotes allow you to create multiline strings. The format() function uses replacement fields written with { } as placeholders.
String formatting characters
| Character | Use |
|---|---|
| %E | Prints exponential notation in upper case. |
String methods and practice
The chapter asks you to practise string tasks such as finding a string's length, counting word occurrences, adding a prefix to lines, and removing a character. Other tasks include making a mirror image, swapping strings, replacing text without replace(), and counting characters, words and lines.
Methods to study
- capitalize()
- swapcase()
- count()
Remember: Remember that Python strings are immutable: you cannot change one character by assigning to its index.
Questions students ask
Short, direct answers to what students search for in this chapter.
What is a string in Python?
A string is a sequence of Unicode characters enclosed in single, double, or triple quotes. It can contain letters, numbers, or special symbols. Python strings are immutable, which means their characters cannot be changed after the string is defined.
How does indexing work in a Python string?
Python assigns an index, or subscript, to each character. Positive indexing starts with 0 at the first character and ends with n-1. Negative indexing starts with -1 at the last character and counts backwards toward the first character.
How do you slice a string in Python?
Use the format str[start:end] to take part of a string. The start index is included, but the end index is not. You can leave out the start or end value. A third value sets the stride, and a negative stride reads the characters in reverse order.
Can you change a character in a Python string?
No. Python strings are immutable, so assigning a new value to one character or deleting one character is not allowed. You can assign a completely new string to the variable. The replace() function returns a string with replacements, but does not change the original string.
What do +, +=, and * do with Python strings?
The + operator concatenates strings by joining them. The += operator appends a string to the end of an existing string. The * operator repeats a string the specified number of times.
How do you format a string with the % operator in Python?
Use format markers such as %s for a string and %d for a signed decimal integer. Put the matching values after the string using the % operator. Python replaces each marker with its corresponding value.
Show 8 more questions
What does the format() function do in Python strings?
The format() function inserts values into a string. Curly braces { } act as replacement fields. The values are supplied to format() in order, and they replace the corresponding fields.
What does find() return if a substring is missing?
The find() function returns -1 if the requested substring does not occur in the string or within the specified search range. If it is found, the function returns the index where the first occurrence begins.
What do in and not in do with strings?
The in and not in operators check whether one string is present in another. They are called membership operators. A program can use the result to choose an action, such as displaying Found or Not Found.
What does it mean that strings are immutable in Python?
Strings are immutable, which means that once a string is defined, it cannot be changed during execution. A program that needs a changed string can build another string, as in a program that removes vowels.
Can you modify a string in Python?
No. Python strings are immutable, which means their characters cannot be changed by assigning a new value to an index. You can create another string using operations such as concatenation or slicing.
What is slicing in Python?
Slicing selects part of a string using the slicing operator [ ]. A slice can include a stride as its third argument. String subscripts can be positive or negative, and str1[::-1] reverses a string.
Which operator is used for string concatenation in Python?
The + operator is used to concatenate strings. Concatenation joins strings together. The * operator repeats a string, while in and not in check whether a string is present in another string.
What are replacement fields in Python format()?
Replacement fields are placeholders written using { }. They are used with the format() function, which replaces the placeholders with the supplied values. Triple quotes can be used to create multiline strings.
Book back answers
20 textbook exercises, solved and checked against the book. Questions we could not prove are left out.
Choose the best answer (1 Mark)
Which of the following is the output of the following python code? str1="TamilNadu" print(str1[::-1])
- (a) Tamilnadu
- (b) Tmlau
- (c) udanlimaT
- (d) udaNlimaT
Try it, then show the answerAnswer
(c) udanlimaT
A negative stride prints the string in reverse order.
From the book: “If you specify a negative value, it prints in reverse order.”
What will be the output of the following code? str1 = "Chennai Schools" str1[7] = "-"
- (a) Chennai-Schools
- (b) Chenna-School
- (c) Type error
- (d) Chennai
Try it, then show the answerAnswer
(c) Type error
Strings are immutable, so assigning a new value to one character is not allowed.
From the book: “strings in python are immutable. That means, once you define a string modifications or deletion is not allowed.”
Which of the following operator is used for concatenation?
- (a) +
- (b) &
- (c) *
- (d) =
Try it, then show the answerAnswer
(a) +
The plus operator joins two or more strings.
From the book: “The plus (+) operator is used to concatenate strings in python.”
Defining strings within triple quotes allows creating:
- (a) Single line Strings
- (b) Multiline Strings
- (c) Double line Strings
- (d) Multiple Strings
Try it, then show the answerAnswer
(b) Multiline Strings
Triple quotes allow a string to span multiple lines.
From the book: “Defining strings within triple quotes also allows creation of multiline strings.”
Practice
What does it mean that Python strings are immutable?
Exam questions
Practice questions with model answers. These are not from an official paper.
What is a Python string, and what does immutable mean?2 marks
A string is a sequence of Unicode characters enclosed in single, double, or triple quotes. Immutable means that once defined, the string cannot be changed during execution.
How do positive and negative subscripts identify characters in a string?2 marks
Positive subscripts begin at 0 for the first character and increase towards the end. Negative subscripts begin at -1 for the last character and count backwards.
What is string slicing, and how does the end value work?2 marks
Slicing takes a substring from a main string using the [ ] operator and index values. The end value is excluded, so Python takes characters up to one position before it.
Explain the use of the +, +=, and * operators with strings.5 marks
Python provides operators to join, append and repeat strings. These operators are useful for string operations.
- Concatenation (+): The + operator joins two or more strings to form one string.
- Example of +: The strings "welcome" and "Python" combine to give "welcomePython".
- Append (+=): The += operator adds a new string to the end of an existing string.
- Example of +=: Appending "Learn Python" to "Welcome to " produces "Welcome to Learn Python".
- Repeating (*): The multiplication operator displays a string multiple times.
- Example of *: Multiplying "Welcome " by 4 displays the string four times.
Example: str1="Welcome " print (str1*4) Output: Welcome Welcome Welcome Welcome
Thus, + joins strings, += appends a string, and * repeats a string.
Watch out
- Do not assume a slice includes its end index; Python excludes that index.
- Do not confuse assigning a new string to a variable with changing a character inside an existing string.
Still stuck on this lesson?
Get an AI answer grounded in your actual textbook — with the exact page reference.
Ask AI about this topic →