A string is a sequence of characters enclosed in single (‘ ’), double (“ ”), or triple quotes (‘’’ ’’’ or “”” “””).
✅ Examples:
name = 'Sakshi'
college = "Government Polytechnic Dehradun"
para = '''This is
a multi-line
string.'''

Each character in a string has an index.
| Character | S | a | k | s | h | i |
|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
| Reverse Index | -6 | -5 | -4 | -3 | -2 | -1 |
✅ Example:
name = "Sakshi"
print(name[0]) # S
print(name[-1]) # i
You can extract part of a string using slicing:
✅ Syntax:
string[start:end:step]
✅ Examples:
name = "Sakshi"
print(name[0:3]) # Sak
print(name[2:]) # kshi
print(name[:4]) # Saks
print(name[::-1]) # ihskaS (reversed string)
✅ Combine strings:
a = "Hello"
b = "Sakshi"
print(a + " " + b) # Hello Sakshi
✅ Repeat strings:
print("Hi! " * 3) # Hi! Hi! Hi!
Here’s a list of the most useful string methods:
| Method | Description | Example |
|---|---|---|
| upper() | Converts to uppercase | "sakshi".upper() → SAKSHI |
| lower() | Converts to lowercase | "HELLO".lower() → hello |
| title() | Capitalizes each word | "python programming".title() |
| capitalize() | Capitalizes first letter | "sakshi".capitalize() |
| strip() | Removes spaces | " hello ".strip() |
| replace(a,b) | Replace substring | "good".replace("good","best") |
| split() | Split into list | "a,b,c".split(",") |
| join() | Join list into string | " ".join(["I","am","Sakshi"]) |
| count() | Count occurrences | "banana".count("a") |
| find() | Find index of substring | "apple".find("p") |
| startswith() | Checks start | "Python".startswith("Py") |
| endswith() | Checks end | "file.txt".endswith(".txt") |
| isalpha() | True if all letters | "Hello".isalpha() |
| isdigit() | True if all digits | "123".isdigit() |
| isalnum() | True if letters & numbers | "abc123".isalnum() |
| swapcase() | Swaps case | "SakShi".swapcase() → sAKsHI |
name = "Sakshi"
age = 20
print(f"My name is {name} and I am {age} years old.")
print("My name is {} and I am {} years old.".format("Sakshi", 20))
print("My name is %s and I am %d years old." % ("Sakshi", 20))
Used to insert special characters.
| Escape | Description |
|---|---|
| \n | New line |
| \t | Tab space |
| \\ | Backslash |
| \' | Single quote |
| \" | Double quote |
✅ Example:
print("Hello\nSakshi") # new line
print("She said: \"Hi!\"")
Strings can be compared using comparison operators (==, <, >):
print("apple" == "apple") # True
print("Apple" < "banana") # True (lexicographically)
You can loop through each character in a string.
✅ Example:
for ch in "Sakshi":
print(ch)
✅ Example:
sentence = "Python is amazing"
print("Python" in sentence) # True
print("Java" not in sentence) # True
Strings are immutable → once created, they cannot be changed.
✅ Example:
name = "Sakshi"
# name[0] = 'R' ❌ Error
name = "Rakshi" # ✅ New string created
s = input("Enter a string: ")
if s == s[::-1]:
print("Palindrome")
else:
print("Not Palindrome")