Chapter 6: Strings in Python
A string is a sequence of characters enclosed in single quotes ('...'), double quotes ("..."), or triple quotes ('''...''' for multi-line strings). In Python, strings are immutable, meaning their contents cannot be changed after they are created.
6.1 String Operations
Python provides several powerful operators to manipulate strings.
- Concatenation (
+): Joins two strings together."Hello" + " World" # Output: 'Hello World' - Repetition (
*): Repeats a string a specified number of times."Py" * 3 # Output: 'PyPyPy' - Membership (
in,not in): Checks if a substring exists within a string."a" in "Apple" # Output: False (case-sensitive) - Slicing (
[start:stop:step]): Extracts a portion of the string.text = "COMPUTER" print(text[1:4]) # Output: 'OMP' print(text[::-1]) # Output: 'RETUPMOC' (Reverses string)
6.2 Traversing a String
You can access each character of a string one by one using a for or while loop.
word = "PYTHON"
for char in word:
print(char)
6.3 Built-in String Methods
Strings come with numerous built-in methods. Note that string methods do not modify the original string; they return a new string.
len(str): Returns the length (number of characters) of the string.capitalize(): Capitalizes the first letter of the string.title(): Capitalizes the first letter of every word.lower()/upper(): Converts the string to all lowercase or all uppercase.count(sub): Returns the number of times substringsubappears.find(sub)/index(sub): Returns the lowest index wheresubis found.find()returns -1 if not found, whileindex()raises an error.startswith(prefix)/endswith(suffix): Returns True if string starts/ends with the specified substring.isalnum(): True if all characters are alphanumeric (letters or numbers).isalpha(): True if all characters are alphabets.isdigit(): True if all characters are digits.islower()/isupper()/isspace(): Checks if all characters are lowercase, uppercase, or whitespace respectively.lstrip()/rstrip()/strip(): Removes leading, trailing, or both leading and trailing whitespace characters.replace(old, new): Replaces occurrences of theoldsubstring withnew.split(sep): Splits the string into a list of words usingsepas the delimiter.partition(sep): Splits the string into a tuple of 3 elements: (before sep, sep, after sep).join(iterable): Joins elements of an iterable (like a list) into a single string, using the string as a separator."-".join(["A", "B", "C"]) # Output: 'A-B-C'
Competency Based Questions
Q1. Predict the Output What is the output of the following code block?
s = " Kendriya Vidyalaya "
s = s.strip()
print(s.replace("a", "@").split())
Q2. Find the Error
Riya wants to change the first letter of her name stored in a variable name = "riya" to a capital letter by directly modifying the character at index 0.
name = "riya"
name[0] = "R"
print(name)
Why does this code throw an error? How can she achieve her goal using string methods?
Q3. Case-Based Scenario A password verification system requires a password to satisfy the following rules:
- It must contain only letters and numbers (no special characters).
- It must end with “123”. Which two Python string methods should the programmer use to verify these conditions?
Q4. Application-Oriented Write a Python program to input a string and determine whether it is a palindrome or not without using any loops. (A palindrome reads the same forwards and backwards, e.g., “MADAM”).
Answers to Competency Based Questions
A1.
['Kendriy@', 'Vidy@l@y@']
Explanation:
strip()removes leading/trailing spaces ->"Kendriya Vidyalaya"replace("a", "@")->"Kendriy@ Vidy@l@y@"split()splits by space into a list ->['Kendriy@', 'Vidy@l@y@'].
A2.
Error: Strings in Python are immutable. You cannot assign a value to a specific index of an existing string (name[0] = "R" causes a TypeError).
Correction: She should use the capitalize() or title() method.
name = "riya"
name = name.capitalize()
print(name)
A3. The programmer should use:
isalnum()(Returns True if characters are only letters and numbers).endswith("123")(Returns True if the string ends with “123”).
A4.
text = input("Enter a string: ")
# Reversing the string using slicing
reversed_text = text[::-1]
if text == reversed_text:
print("It is a palindrome")
else:
print("It is not a palindrome")