1. Introduction to Strings
A string is an ordered sequence of characters (letters, digits, symbols, spaces) enclosed within single quotes ('), double quotes ("), or triple quotes (""" or ''').
In Python, strings are objects of the built-in str class and are immutable (cannot be modified after creation).
2. Creating Strings
# Single quotes
s1 = 'Hello'
# Double quotes
s2 = "Python"
# Triple quotes (multi-line strings)
s3 = """This is a
multi-line
string."""
# Empty string
empty = ""
# String from input
name = input("Enter name: ")3. String Indexing
Each character in a string has a position called an index. Indexing starts from 0.
text = "Python"
# Index: 0 1 2 3 4 5
# Characters: P y t h o n
print(text[0]) # P
print(text[2]) # t
print(text[-1]) # n (negative index: last character)
print(text[-3]) # h (third from end)Important: Attempting to access an index outside the range raises IndexError.
4. String Slicing
Slicing extracts a portion of a string. Syntax: string[start:stop:step]
text = "Python Programming"
print(text[0:6]) # Python (index 0 to 5)
print(text[7:18]) # Programming
print(text[:6]) # Python (start defaults to 0)
print(text[7:]) # Programming (stop defaults to end)
print(text[::2]) # Pto rgamn (every 2nd char)
print(text[::-1]) # gnimmargorP nohtyP (reverse)
print(text[-11:-4]) # Progra (negative indices)5. Strings are Immutable
Strings cannot be changed after creation. Any operation that modifies a string creates a new string.
text = "Hello"
# text[0] = "J" # TypeError: 'str' object does not support item assignment
# Correct way: create a new string
text = "J" + text[1:] # "Jello"6. String Operators
| Operator | Description | Example | Result |
|---|---|---|---|
| + | Concatenation | "Hello" + " World" | Hello World |
| * | Repetition | "Ha" * 3 | HaHaHa |
| in | Membership test | "Py" in "Python" | True |
| not in | Membership test | "Java" not in "Python" | True |
| == | Equality check | "abc" == "abc" | True |
| > | Lexicographic comparison | "abc" > "abd" | False |
7. Traversing a String
# Using for loop (by character)
for char in "Python":
print(char)
# Using for loop with index
text = "Python"
for i in range(len(text)):
print(f"Index {i}: {text[i]}")8. String Methods
| Method | Description | Example | Result |
|---|---|---|---|
| upper() | Converts to uppercase | "hello".upper() | HELLO |
| lower() | Converts to lowercase | "HELLO".lower() | hello |
| capitalize() | Capitalizes first letter | "python".capitalize() | Python |
| title() | Title case | "hello world".title() | Hello World |
| strip() | Removes leading/trailing whitespace | " Hello ".strip() | Hello |
| lstrip() | Removes leading whitespace | " Hello".lstrip() | Hello |
| rstrip() | Removes trailing whitespace | "Hello ".rstrip() | Hello |
| find(sub) | Returns index of first occurrence | "Python".find("th") | 1 |
| index(sub) | Like find but raises ValueError | "Python".index("th") | 1 |
| count(sub) | Counts occurrences | "banana".count("a") | 3 |
| replace(old, new) | Replaces occurrences | "Hello".replace("l", "x") | Hexxo |
| split(sep) | Splits into list | "a,b,c".split(",") | ["a", "b", "c"] |
| join(list) | Joins list into string | ",".join(["a", "b"]) | a,b |
| startswith(prefix) | Checks prefix | "Python".startswith("Py") | True |
| endswith(suffix) | Checks suffix | "Python".endswith("on") | True |
| isalpha() | Checks if all alphabets | "abc".isalpha() | True |
| isdigit() | Checks if all digits | "123".isdigit() | True |
| isalnum() | Checks if alphanumeric | "abc123".isalnum() | True |
| isspace() | Checks if all whitespace | " ".isspace() | True |
| len() | Returns length (built-in function) | len("Python") | 6 |
9. String Formatting
# f-strings (Python 3.6+)
name = "Riya"
age = 17
print(f"My name is {name} and I am {age} years old.")
# format() method
print("My name is {} and I am {} years old.".format(name, age))
# % formatting
print("My name is %s and I am %d years old." % (name, age))10. Unicode and ASCII
Python strings support Unicode, allowing characters from all languages.
# ord() - returns Unicode code point
print(ord("A")) # 65
print(ord("a")) # 97
print(ord("0")) # 48
# chr() - returns character from code point
print(chr(65)) # A
print(chr(97)) # a
# Unicode characters
print("\u0041") # A
print("\U0001F600") # smiley emoji11. Escape Sequences
| Sequence | Meaning |
|---|---|
| \n | Newline |
| \t | Tab |
| \\ | Backslash |
| \' | Single quote |
| \" | Double quote |
print("Line1\nLine2") # Two lines
print("Column1\tColumn2") # Tab-separated12. Revision Questions and Answers
Very Short Answer Questions
1. What is a string in Python?
An ordered sequence of characters enclosed in quotes.
2. Are strings mutable or immutable?
Immutable.
3. Which operator is used to concatenate two strings?
+ operator.
4. What does the len() function return?
The length (number of characters) of the string.
5. How do you extract a substring from a string?
Using slicing: string[start:stop].
Short Answer Questions
1. Explain string slicing with positive and negative indices.
Slicing extracts a portion using str[start:stop:step]. Positive indices count from beginning (0), negative from end (-1). Example: "Python"[-3:-1] returns "ho". Omitting start defaults to 0, omitting stop defaults to end.
2. Explain any five string methods with examples.
upper() converts to uppercase, lower() converts to lowercase, split() splits into list, join() joins list into string, replace() replaces substrings.
Long Answer Questions
1. Write a Python program to count the number of vowels and consonants in a given string.
text = input("Enter string: ").lower(); vowels = consonants = 0; for ch in text: if ch.isalpha(): if ch in "aeiou": vowels += 1; else: consonants += 1; print(f"Vowels: {vowels}, Consonants: {consonants}")
2. Write a program to check if a string is a palindrome (reads same forwards and backwards).
text = input("Enter string: "); if text == text[::-1]: print("Palindrome"); else: print("Not a palindrome")