Humanities/Arts Exam  >  Humanities/Arts Notes  >  Computer Science for Class 11  >  Chapter Notes: Strings

Strings Chapter Notes | Computer Science for Class 11 - Humanities/Arts PDF Download

Introduction

We learned that a sequence is an organized collection of items, with each item indexed by an integer. We also got a brief introduction to various sequence data types in Python, including:

  • Strings
  • Lists
  • Tuples

Additionally, we were introduced to the Dictionary data type, which falls under the category of mapping. In this chapter, we will explore strings in detail. 

Strings in Python

A string in Python is a collection of one or more Unicode characters. These characters can be letters, digits, whitespace, or any other symbols. To create a string, you can enclose characters in single, double, or triple quotes.

Example:
str1 = 'Hello World!'
str2 = "Hello World!"
str3 = """Hello World!"""
str4 = '''Hello World!'''

In this example, str1, str2, str3, and str4 all contain the same string value, 'Hello World!'. The values in str3 and str4 can span multiple lines because they are enclosed in triple quotes.

For instance:
str3 = """Hello World! welcome to the world of Python"""
str4 = '''Hello World! welcome to the world of Python'''

Python does not have a separate character data type; a string of length one is considered a character.

Accessing Characters in a String

Indexing is the method used to access individual characters within a string. The index indicates which character to retrieve from the string and is enclosed in square brackets ( [ ] ). In Python, the index of the first character (from the left) is 0, while the index of the last character is n-1, where n is the length of the string. If an index outside this range is specified, an IndexError will occur. The index must be an integer, which can be positive, zero, or negative.

Example:

Initializing a string

  • str1 = 'Hello World!' 
  • Accessing Characters
  • First character: str1[0] Output: 'H' 
  • Seventh character: str1[6] Output: 'W' 
  • Last character:str1[11] Output: '!' 
  • Out of Range Error: str1[15] Error: IndexError: string index out of range 

Using Expressions for Indexing

  • Valid Expression: str1[2+4] Output: 'W' (6th character) 
  • Invalid Expression: str1[1.5] Error: TypeError: string indices must be integers 

Negative Indexing

  • str1[-1] Output: '!' (first character from right) 
  • str1[-12] Output: 'H' (last character from right) 

Indexing of Characters in the String 'Hello World!'

Strings Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Using the len() Function

  • The len() function in Python returns the length of the string provided as an argument. For instance, the length of the string str1 = 'Hello World!' is 12.
  • Example Usage:
  • Getting Length: len(str1) 
  • Assigning Length: n = len(str1) 
  • Printing Length: print(n) 

Accessing Characters Using Length

  • Last Character: str1[n-1] 
  • First Character: str1[-n]  Output: 'H' 

Strings are Immutable

In Python, strings are considered immutable data types. This means that once a string is created, its contents cannot be changed. If you try to modify a string after it has been created, it will result in an error.

For example, if we have a string str1 = "Hello World!" and we attempt to replace the character 'e' with 'a' using str1[1] = 'a', Python will raise a TypeError because strings do not support item assignment.

String Operations

Introduction: Python permits various operations on strings, including concatenation, repetition, membership, and slicing. A string is essentially a sequence of characters, and these operations allow for different ways to manipulate and interact with string data.

Concatenation in Python

Concatenation refers to the process of joining two strings together. In Python, this can be done using the concatenation operator, which is the plus sign ( + ).

Example:

Code:
str1 = 'Hello' # First string str2 = 'World!' # Second string result = str1 + str2 # Concatenated strings print(result) 

Output:
 'HelloWorld!' 

Explanation:

  • In this example, we have two strings:  str1  containing 'Hello' and  str2  containing 'World!'.
  • By using the concatenation operator ( + ), we join these two strings together to form 'HelloWorld!'.
  • It's important to note that  str1 and  str2 remain unchanged after this operation.
  • You can verify this by printing  str1 and str2 after the concatenation.

Example:
Code:
print(str1) # Output: 'Hello' print(str2) # Output: 'World!' 

Repetition in Python

Repetition in Python allows you to repeat a given string multiple times using the repetition operator, which is denoted by the symbol *.

Example:
Code:
str1 = 'Hello' # Repeat the value of str1 2 times result1 = str1 * 2 print(result1) # Repeat the value of str1 5 times result2 = str1 * 5 print(result2) 

Output:
'HelloHello' 'HelloHelloHelloHelloHello' 

Explanation:

  • In this example, we assign the string 'Hello' to the variable  str1.
  • Then, we use the repetition operator ( * ) to repeat the value of  str1.
  • When we repeat  str1 2 times, we get 'HelloHello'. When we repeat it 5 times, we get 'HelloHelloHelloHelloHello'.
  • It's important to note that  str1 itself remains the same after using the repetition operator.

Membership in Python

In Python, there are two membership operators: 'in' and 'not in'. These operators are used to check whether a substring exists within a string.

'in' Operator

  • The 'in' operator takes two strings as input.
  • It returns True if the first string (substring) is found within the second string (the main string).
  • If the substring is not found, it returns False.

For example:

Example:

str1 = "Welcome to my world"

  • 'W' in str1. Checks if 'W' is in str1 (True)
  • 'Wor' in str1. Checks if 'Wor' is in str1 (True)
  • 'My' in str1. Checks if 'My' is in str1 (True)

'not in' Operator

  • The 'not in' operator also takes two strings as input.
  • It returns True if the first string (substring) is not found within the second string (the main string).
  • If the substring is found, it returns False.

For example:

Example:

str1 = "Welcome to my world"

  • 'My' not in str1. Checks if 'My' is not in str1 (False)
  • 'Hello' not in str1. Checks if 'Hello' is not in str1 (True)

Slicing in Strings

  • In Python, slicing is a method used to access a specific part of a string or substring by specifying an index range.
  • To illustrate this, let’s consider a string str1. The slice operation str1[n:m] returns a portion of the string starting from index n (inclusive) and ending at index m (exclusive).
  • For example, str1[1:5] would give us the substring starting from index 1 to 4, resulting in 'ello'.
  • Similarly, str1[7:10] returns the substring from index 7 to 9, yielding 'orl'.
  • If the specified index is too large, like str1[3:20], it gets truncated to the end of the string, producing 'lo World!'.
  • If the first index is omitted, the slice starts from the beginning of the string, as in str1[:5] which returns 'Hello'.
  • Conversely, if the second index is not specified, slicing continues to the end of the string, such as in str1[6:] which gives 'World!'.

Step Size in Slicing

  • The slice operation can also include a third index that indicates the step size, using the format str1[n:m:k]. This means that every k-th character will be extracted from the string str1, starting from index n and ending at m-1.
  • For instance, str1[0:10:2] extracts every 2nd character from index 0 to 9, resulting in 'HloWr', while str1[0:10:3] gives 'HlWl'.

Negative Indexing in Slicing

  • Python also allows the use of negative indexes for slicing. For example, str1[-6:-1] slices the characters at indexes -6, -5, -4, -3, and -2, resulting in 'World'.
  • Additionally, by omitting both indexes and specifying a step size of -1, such as in str1[::-1], the string is reversed, producing '!dlroW olleH'.

Traversing a String

We can access or traverse each character of a string using either a for loop or a while loop.

(A) String Traversal Using for Loop:

  • When we use a for loop to traverse a string, it automatically starts from the first character and continues until the last character is reached.
  • Here’s an example:
    str1 = 'Hello World!' for ch in str1: print(ch, end = '') 

Output: Hello World!

(B) String Traversal Using while Loop:

  • In a while loop, we need to manually manage the index to access each character of the string.
  • The loop continues until the index is less than the length of the string.
  • Here’s how it works:
    str1 = 'Hello World!' index = 0 while index < len(str1): print(str1[index], end = '') index += 1 

Output: Hello World!

  • In this example, the while loop runs as long as the condition index < len(str1) is true, with index ranging from 0 to len(str1) - 1.

String Methods and Built-In Functions

Python offers various built-in functions for working with strings. The table below outlines some of the commonly used built-in functions for string manipulation.

Built-in Functions for String Manipulation

Strings Chapter Notes | Computer Science for Class 11 - Humanities/ArtsStrings Chapter Notes | Computer Science for Class 11 - Humanities/ArtsStrings Chapter Notes | Computer Science for Class 11 - Humanities/ArtsStrings Chapter Notes | Computer Science for Class 11 - Humanities/ArtsStrings Chapter Notes | Computer Science for Class 11 - Humanities/ArtsStrings Chapter Notes | Computer Science for Class 11 - Humanities/ArtsStrings Chapter Notes | Computer Science for Class 11 - Humanities/ArtsStrings Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Handling Strings in Python

In this section, we will explore user-defined functions in Python that allow us to perform various operations on strings. Strings are a fundamental data type in Python, and understanding how to manipulate them using functions can greatly enhance our programming skills.

Let's delve into a specific program that demonstrates how to count the occurrences of a character in a given string using a user-defined function.
Program: Write a program with a user defined function to count the number of times a character (passed as argument) occurs in the given string.

Strings Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Output:
Enter a string: 
Today is a Holiday Enter the character to be searched: a Number of times character a occurs in the string is: 3

Program: Write a program with a user defined function with string as a parameter which replaces all vowels in the string with '*'.

Strings Chapter Notes | Computer Science for Class 11 - Humanities/Arts
Output: 
Enter a String: Hello World 
The original String is: Hello World 
The modified String is: H*ll* W*rld

Program: Write a program to input a string from the user and print it in the reverse order without creating a new string.

Strings Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Program: Write a program which reverses a string passed as parameter and stores the reversed string in a new string. Use a user defined function for reversing the string.

Strings Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Program: Write a program using a user defined function to check if a string is a palindrome or not. (A string is called palindrome if it reads same backwards as forward. For example, Kanak is a palindrome.) 


Strings Chapter Notes | Computer Science for Class 11 - Humanities/Arts

The document Strings Chapter Notes | Computer Science for Class 11 - Humanities/Arts is a part of the Humanities/Arts Course Computer Science for Class 11.
All you need of Humanities/Arts at this link: Humanities/Arts
33 docs|11 tests

FAQs on Strings Chapter Notes - Computer Science for Class 11 - Humanities/Arts

1. What are strings in Python and how are they defined?
Ans. In Python, strings are sequences of characters enclosed within single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """). They can include letters, numbers, symbols, and whitespace. Strings are immutable, which means once they are created, their content cannot be changed.
2. What are some common operations that can be performed on strings in Python?
Ans. Common operations on strings in Python include concatenation (joining strings using the `+` operator), repetition (using the `*` operator), slicing (extracting parts of a string), and checking for membership using the `in` keyword. Strings can also be compared using relational operators.
3. How can you traverse a string in Python?
Ans. You can traverse a string in Python using loops, such as a `for` loop or a `while` loop. For example, using a `for` loop, you can iterate through each character in the string: python for char in "Hello": print(char) This will print each character of the string "Hello" on a new line.
4. What are some commonly used string methods in Python?
Ans. Some commonly used string methods in Python include `str.upper()` to convert a string to uppercase, `str.lower()` to convert to lowercase, `str.strip()` to remove whitespace from the beginning and end, `str.split()` to split a string into a list based on a delimiter, and `str.replace()` to replace parts of the string with another string.
5. How do built-in functions interact with strings in Python?
Ans. Built-in functions in Python can be used with strings to perform various tasks. For example, `len()` returns the length of a string, `str()` converts other data types to a string, and `sorted()` can sort the characters in a string. These functions allow you to manipulate and analyze strings efficiently.
Related Searches

Extra Questions

,

pdf

,

Free

,

ppt

,

Strings Chapter Notes | Computer Science for Class 11 - Humanities/Arts

,

Exam

,

Important questions

,

Summary

,

mock tests for examination

,

video lectures

,

shortcuts and tricks

,

Sample Paper

,

Strings Chapter Notes | Computer Science for Class 11 - Humanities/Arts

,

past year papers

,

Strings Chapter Notes | Computer Science for Class 11 - Humanities/Arts

,

Semester Notes

,

Previous Year Questions with Solutions

,

Viva Questions

,

MCQs

,

practice quizzes

,

study material

,

Objective type Questions

;