Below is a complete, detailed, and exam-oriented explanation of Strings in Python, including ALL major operations, functions, and methods.
STRINGS IN PYTHON
What is a String?
A string is a sequence of characters enclosed in:
- Single quotes →
'hello' - Double quotes →
"hello" - Triple quotes →
"""hello"""(for multi-line strings)
Characteristics of Strings
✔ Ordered (indexed)
✔ Immutable (cannot be modified)
✔ Iterable (can loop through characters)
✔ Supports slicing
✔ Can hold Unicode text (supports all languages)
1. Creating Strings
s1 = 'Hello'
s2 = "Python"
s3 = """Multi
line
string"""
2. Accessing String Characters (Indexing)
Positive indexing:
s = "Python"
print(s[0]) # P
print(s[3]) # h
Negative indexing:
print(s[-1]) # n
print(s[-3]) # h
3. Slicing Strings
Syntax:
string[start : end : step]
Examples:
s = "Programming"
print(s[0:5]) # Progr
print(s[:7]) # Program
print(s[3:]) # gramming
print(s[::-1]) # Reverse string
4. String Immutability
Strings cannot be modified:
s = "Hello"
s[0] = 'h' # ❌ Error
To modify:
s = 'h' + s[1:]
5. String Operations
1. Concatenation (+)
"Hello " + "World"
2. Repetition (*)
"Hi" * 3 # HiHiHi
3. Membership (in, not in)
"Py" in "Python" # True
4. Comparison
"abc" == "abc"
"apple" < "banana"
5. Iteration
for ch in "Python":
print(ch)
6. Length
len("Python") # 6
6. Built-in Functions for Strings
| Function | Description |
|---|---|
len(s) | Length of string |
max(s) | Character with highest ASCII value |
min(s) | Character with lowest ASCII value |
sorted(s) | Returns characters in sorted order |
str(obj) | Converts object to string |
Examples:
s = "python"
print(max(s)) # y
print(sorted(s)) # ['h','n','o','p','t','y']
7. STRING METHODS (VERY IMPORTANT)
Below is a complete list of essential string methods.
A. Case Conversion Methods
1. lower()
Converts to lowercase.
"HELLO".lower()
2. upper()
Converts to uppercase.
"hello".upper()
3. title()
Each word’s first letter becomes uppercase.
"hello world".title()
4. capitalize()
First letter capitalized.
"python programming".capitalize()
5. swapcase()
Uppercase ↔ lowercase.
"HeLLo".swapcase()
B. Search & Find Methods
1. find(sub)
Returns index of substring (or -1).
"hello".find("l") # 2
2. rfind(sub)
Find from right side.
3. index(sub)
Like find() but gives error if substring not found.
4. startswith(prefix)
Checks starting.
"Python".startswith("Py")
5. endswith(suffix)
Checks ending.
C. Modification Methods
1. replace(old, new)
"hello world".replace("world", "Python")
2. strip() / lstrip() / rstrip()
Removes whitespace.
" hello ".strip()
3. join()
Joins list of strings.
"-".join(["a","b","c"])
4. split(sep)
Splits into list.
"apple,banana".split(",")
5. splitlines()
Splits lines in multi-line text.
D. Testing Methods (Return True/False)
1. isalnum() → only letters & numbers
2. isalpha() → only letters
3. isdigit() → only numbers
4. islower() / isupper()
5. isspace() → only whitespace
6. istitle()
Examples:
"123".isdigit() # True
"Hello".isalpha() # True
E. Alignment and Formatting Methods
1. center(width)
"Hi".center(10)
2. ljust() / rjust()
Left/right alignment.
3. zfill(width)
Pads number with zeros.
"42".zfill(5) # 00042
8. Escape Sequences
| Escape | Meaning |
|---|---|
\n | New line |
\t | Tab |
\\ | Backslash |
\' | Single quote |
\" | Double quote |
Example:
print("Hello\nWorld")
9. Raw Strings
Used to ignore escape sequences:
s = r"C:\new\folder"
10. String Formatting
1. f-strings (best method)
name = "John"
print(f"My name is {name}")
2. format()
"{} scored {}".format("John", 90)
3. % formatting
print("Age = %d" % 25)
11. Important String Programs
1. Reverse String
s = "Python"
print(s[::-1])
2. Count vowels
vowels = 0
s = "Education".lower()
for ch in s:
if ch in "aeiou":
vowels += 1
print(vowels)
3. Check Palindrome
s = "madam"
print(s == s[::-1])
4. Remove all spaces
"Python Programming".replace(" ", "")
5. Frequency of characters
s = "apple"
freq = {}
for ch in s:
freq[ch] = freq.get(ch, 0) + 1
print(freq)
SUMMARY TABLE
| Category | Methods |
|---|---|
| Case change | lower, upper, title, capitalize, swapcase |
| Search | find, rfind, index, startswith, endswith |
| Modify | replace, strip, split, join |
| Testing | isdigit, isalpha, isalnum, isspace, islower, isupper |
| Alignment | center, ljust, rjust, zfill |
