Strings
Strings — Study Notes
NCERT-aligned · 9 notes · 3 shown free
8.1 INTRODUCTION
Explanation8.1 INTRODUCTION
In Chapter 5, students were introduced to the concept of sequences, which are orderly collections of items where each item is indexed by an integer. Python provides several sequence data types, including strings, lists, and tuples. Additionally, a different data type called 'Dictionary' was introduced, which falls under the category of mappings rather than sequences. This chapter focuses exclusively on strings, exploring their properties, operations, and methods in detail. While lists, tuples, and dictionaries were briefly introduced earlier, their detailed study is reserved for subsequent chapters: lists in Chapter 9, and tuples and dictionaries in Chapter 10. Understanding strings is fundamental because they are widely used in programming for storing and manipulating textual data. This chapter will build upon the foundational knowledge of sequences and provide a comprehensive overview of string handling in Python.
- Sequences are ordered collections indexed by integers.
- Python sequence data types include strings, lists, and tuples.
- Dictionaries are mapping types, not sequences.
- This chapter focuses on strings in detail.
- Lists, tuples, and dictionaries are covered in later chapters.
- Strings are essential for handling textual data in programming.
- 📌 Sequence: An ordered collection of items indexed by integers.
- 📌 String: A sequence of Unicode characters enclosed in quotes.
- 📌 Dictionary: A mapping data type associating keys with values.
8.2 STRINGS
Explanation8.2 STRINGS
A string in Python is a sequence made up of one or more Unicode characters. These characters can be letters, digits, whitespace, or any other symbols. Strings are created by enclosing characters within single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """). Triple quotes allow strings to span multiple lines, making them useful for longer text blocks or documentation strings. Python does not have a separate character data type; a string of length one is considered a character. For example, the variables str1, str2, str3, and str4 can all hold the same string value 'Hello World!' when enclosed in different types of quotes. Using triple quotes, strings can be extended over multiple lines without the need for explicit newline characters. This flexibility in string declaration is important for writing readable and maintainable code. Strings are immutable sequences, meaning their contents cannot be changed once created, a concept explored further in section 8.2.2.
- Strings are sequences of one or more Unicode characters.
- Characters can be letters, digits, whitespace, or symbols.
- Strings can be enclosed in single, double, or triple quotes.
- Triple quotes allow multi-line strings.
- Python has no separate character data type; single-character strings are used.
- Strings are immutable sequences.
- 📌 Unicode: A standard for encoding characters from all writing systems.
- 📌 Immutable: Cannot be changed after creation.
8.2.1 Accessing Characters in a String
Explanation8.2.1 Accessing Characters in a String
Each character in a string can be accessed individually using indexing. Python uses zero-based indexing, meaning the first character is at index 0, the second at index 1, and so on up to n-1 where n is the length of the string. Indexing is done by pl
Practice Questions — Strings
Includes NCERT exercise questions with answers
Q1.1. Consider the following string mySubject: ```python 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.startsworth('Comp')) x. print(mySubject.isalpha())
Answer:
Let's analyze each operation step-by-step: i. print(mySubject[0:len(mySubject)]) - This prints the substring from index 0 to the length of the string (exclusive), which is the entire string. - Output: 'Computer Science' ii. print(mySubject[-7:-1]) - Negative indices count from the end. -1 is last character. - So indices from -7 to -1 (exclusive) correspond to characters from index len(mySubject)-7 to len(mySubject)-1. - 'Science' is at the end, 'Science' length 7, so -7:-1 extracts 'Scienc' - Output: 'Scienc' iii. print(mySubject[::2]) - This slices the string with step 2, i.e., every second character starting from index 0. - Characters at indices 0,2,4,... - 'C','m','u','e',' ','c','n','c' - Output: 'Cmue cnc' iv. print(mySubject[len(mySubject)-1]) - Prints the last character of the string. - Last character is 'e' - Output: 'e' v. print(2*mySubject) - Prints the string twice concatenated. - Output: 'Computer ScienceComputer Science' vi. print(mySubject[::-2]) - Prints the string reversed with step -2. - Starting from last character, every second character backwards. - Characters: 'e','c','n',' ','r','t','m' - Output: 'ecn rtm' vii. print(mySubject[:3] + mySubject[3:]) - Concatenates substring from start to 3 and from 3 to end. - This is the original string. - Output: 'Computer Science' viii. print(mySubject.swapcase()) - Swaps case of each character. - 'Computer Science' becomes 'cOMPUTER sCIENCE' - Output: 'cOMPUTER sCIENCE' ix. print(mySubject.startsworth('Comp')) - There is a typo: 'startswith' is correct method. - Assuming typo, mySubject.startswith('Comp') returns True because string starts with 'Comp'. - Output: True x. print(mySubject.isalpha()) - Checks if all characters are alphabets. - Since string contains space, returns False. - Output: False
Explanation:
Each sub-part is explained with Python string slicing and method behavior: - Slicing with positive and negative indices - String repetition - Reversing with step - Case swapping - String methods startswith and isalpha Note: The typo in 'startswith' is noted and corrected in explanation.
Q2.2. Consider the following string myAddress: ```python 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:
Let's analyze each operation step-by-step: i. print(myAddress.lower()) - Converts all characters to lowercase. - Output: 'wz-1, new ganga nagar, new delhi' ii. print(myAddress.upper()) - Converts all characters to uppercase. - Output: 'WZ-1, NEW GANGA NAGAR, NEW DELHI' iii. print(myAddress.count('New')) - Counts occurrences of substring 'New'. - 'New' appears twice. - Output: 2 iv. print(myAddress.find('New')) - Returns index of first occurrence of 'New'. - 'New' starts at index 5. - Output: 5 v. print(myAddress.rfind('New')) - Returns index of last occurrence of 'New'. - Last 'New' starts at index 19. - Output: 19 vi. print(myAddress.split(',')) - Splits string at commas. - Output: ['WZ-1', ' New Ganga Nagar', ' New Delhi'] vii. print(myAddress.split('')) - Splitting by empty string is invalid and raises ValueError. - Output: Error: empty separator viii. print(myAddress.replace('New','Old')) - Replaces all occurrences of 'New' with 'Old'. - Output: 'WZ-1, Old Ganga Nagar, Old Delhi' ix. print(myAddress.partition(',')) - Splits string into tuple at first comma. - Output: ('WZ-1', ',', ' New Ganga Nagar, New Delhi') x. print(myAddress.index('Agra')) - Searches for substring 'Agra'. Not found. - Raises ValueError: substring not found
Explanation:
Each sub-part is explained with Python string methods: - lower(), upper() for case conversion - count() for substring count - find() and rfind() for substring index - split() behavior with valid and invalid separators - replace() for substring replacement - partition() returns tuple - index() raises error if substring not found Note: split('') is invalid and will cause error.
Q3.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 return the new string.
Answer:
To write the function deleteChar(), follow these steps: 1. Define the function deleteChar() with two parameters: input_string (string) and char_to_delete (character). 2. Initialize an empty string result to store the new string. 3. Loop through each character ch in input_string. 4. If ch is not equal to char_to_delete, append ch to result. 5. After the loop ends, return the result string. Example implementation in Python: def deleteChar(input_string, char_to_delete): result = "" for ch in input_string: if ch != char_to_delete: result += ch return result Example usage: input_str = "hello world" char_del = 'l' print(deleteChar(input_str, char_del)) # Output: heo word
Explanation:
The function iterates over each character of the input string and constructs a new string by excluding all occurrences of the specified character. This ensures that all instances of the character are removed from the string.
Q4.Input a string having some digits. Write a function to return the sum of digits present in this string.
Answer:
To find the sum of digits in a string: 1. Define a function sumOfDigits() that takes a string as input. 2. Initialize a variable total_sum to 0. 3. Loop through each character ch in the string. 4. Check if ch is a digit using the isdigit() method. 5. If yes, convert ch to integer and add it to total_sum. 6. After the loop, return total_sum. Example implementation in Python: def sumOfDigits(input_string): total_sum = 0 for ch in input_string: if ch.isdigit(): total_sum += int(ch) return total_sum Example usage: input_str = "abc123xyz" print(sumOfDigits(input_str)) # Output: 6 (1+2+3)
Explanation:
The function checks each character to determine if it is a digit. If it is, it converts it to an integer and adds it to a running total. This way, the sum of all digits in the string is computed.
Q5.Write a function that takes a sentence as an input parameter where each word in the sentence is separated by a space. The function should replace each blank with a hyphen and then return the modified sentence.
Answer:
To replace spaces with hyphens in a sentence: 1. Define a function replaceBlanks() that takes a sentence string as input. 2. Use the string method replace() to replace all spaces (' ') with hyphens ('-'). 3. Return the modified string. Example implementation in Python: def replaceBlanks(sentence): return sentence.replace(' ', '-') Example usage: sentence = "This is a test" print(replaceBlanks(sentence)) # Output: This-is-a-test
Explanation:
The replace() method of strings is used to substitute all occurrences of a specified substring (space) with another substring (hyphen). This effectively replaces all blanks with hyphens.
Q6.Which of the following is NOT a sequence data type introduced in Python Chapter 5?
Answer:
Dictionary
Explanation:
Strings, lists, and tuples are sequence data types introduced in Chapter 5. Dictionary is a mapping data type, not a sequence.
Q7.Which of the following is a correct way to create a multi-line string in Python?
Answer:
Using triple quotes ''' ''' or """ """
Explanation:
Triple quotes (either ''' ''' or """ """) allow strings to span multiple lines in Python.
Q8.In Python, what is the data type of a string of length one?
Answer:
String
Explanation:
Python does not have a separate character data type; a string of length one is still considered a string.
All 11 Chapters in Computer Science
Computer Science · Class 11