Handling Strings in Python
A string is a collection of characters enclosed in single quotes ('
), double quotes ("
), or triple quotes ('''
or """
). Python does not have a separate character type; a single character is considered a string of length 1.
Accessing Characters in a String
Strings are indexed collections, meaning you can access individual characters using their index.
- Forward indexing starts from
0
. - Backward indexing starts from
-1
(last character).

Example:
String1 = "PYTHONFORALL"
print(String1[3]) # Output: H
print(String1[-3]) # Output: A
Remember: Trying to access an index beyond the length of the string will raise an IndexError
.
Escape Sequences in Strings
Escape sequences allow you to include special characters inside a string.
Escape Sequence | Description | Example | Output |
---|---|---|---|
\' | Single Quote | 'Python\'s book' | Python's book |
\" | Double Quote | "Python says \"Hi!\"" | Python says "Hi!" |
\\ | Backslash | "Path: C:\\Program" | Path: C:\Program |
\n | Newline | "Hello\nWorld" | Hello World |
\t | Tab | "Hello\tWorld" | Hello World |
print("Python says \"Learn Strings!\"")
print("Path: C:\\Users\\YourName")
print("Hello\nWorld")
String Operations
1️⃣ Concatenation
Joining two strings using +
operator.
name = "Rhea"
msg = "Hello "
print(msg + name) # Output: Hello Rhea
2️⃣ Repetition
Repeating a string using *
operator.
name = "PythonForAll"
print(name * 4)
3️⃣ Slicing
Extracting a substring using slicing.
name = "PythonForAll"
print(name[0:6]) # Output: Python
print(name[-6:-2]) # Output: ForA
print(name[::-1]) # Output: llAroFnohtyP (Reversed)
Slicing syntax: [start:stop:step]
. Leaving start
or stop
empty defaults to the beginning or end of the string.
Membership Operators
Using in
and not in
to check for substrings.
name = "PythonForAll"
print("on" in name) # Output: True
print("All" not in name) # Output: True
These operators are case-sensitive. "python" in name
would return False
.
Built-In String Functions
Function | Description | Example | Output |
---|---|---|---|
upper() | Converts to uppercase | "hello".upper() | "HELLO" |
lower() | Converts to lowercase | "HELLO".lower() | "hello" |
title() | Converts first letter of each word to uppercase | "hello world".title() | "Hello World" |
capitalize() | Capitalizes first letter | "hello world".capitalize() | "Hello world" |
swapcase() | Toggles case | "PyThOn".swapcase() | "pYtHoN" |
startswith() | Checks prefix | "hello".startswith("he") | True |
endswith() | Checks suffix | "hello".endswith("lo") | True |
find() | Finds substring index | "hello".find("e") | 1 |
rfind() | Finds last occurrence of substring | "hello hello".rfind("l") | 9 |
replace() | Replaces substring | "hello".replace("l", "z") | "hezzo" |
len() | Length of string | len("hello") | 5 |
isalpha() | Checks if all characters are alphabets | "hello".isalpha() | True |
isdigit() | Checks if all characters are digits | "1234".isdigit() | True |
isalnum() | Checks if string is alphanumeric | "Hello123".isalnum() | True |
isspace() | Checks if all characters are spaces | " ".isspace() | True |
strip() | Removes leading/trailing spaces | " hello ".strip() | "hello" |
split() | Splits string into list | "Python For All".split() | ["Python", "For", "All"] |
join() | Joins elements of iterable with a separator | "-".join(["Python", "For", "All"]) | "Python-For-All" |