🧵 Python Strings – Complete Notes

🔹 1. What is a String?

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.'''
 

🔹 2. String Indexing

Each character in a string has an index.

CharacterSakshi
Index012345
Reverse Index-6-5-4-3-2-1

✅ Example:

name = "Sakshi"
print(name[0])   # S
print(name[-1])  # i
 

🔹 3. String Slicing

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)
 

🔹 4. String Concatenation and Repetition

✅ Combine strings:

a = "Hello"
b = "Sakshi"
print(a + " " + b)   # Hello Sakshi
 

✅ Repeat strings:

print("Hi! " * 3)   # Hi! Hi! Hi! 

 

🔹 5. String Methods (Important)

Here’s a list of the most useful string methods:

MethodDescriptionExample
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

🔹 6. String Formatting

✅ f-string (modern way)

name = "Sakshi"
age = 20
print(f"My name is {name} and I am {age} years old.")
 

✅ format() method

print("My name is {} and I am {} years old.".format("Sakshi", 20))

 

✅ Using %

print("My name is %s and I am %d years old." % ("Sakshi", 20))

 

🔹 7. Escape Characters

Used to insert special characters.

EscapeDescription
\nNew line
\tTab space
\\Backslash
\'Single quote
\"Double quote

✅ Example:

print("Hello\nSakshi")   # new line
print("She said: \"Hi!\"")
 

🔹 8. String Comparison

Strings can be compared using comparison operators (==, <, >):

print("apple" == "apple")   # True
print("Apple" < "banana")   # True (lexicographically)
 

🔹 9. String Iteration

You can loop through each character in a string.

✅ Example:

for ch in "Sakshi":
   print(ch)
 

🔹 10. Checking Substrings

✅ Example:

sentence = "Python is amazing"
print("Python" in sentence)   # True
print("Java" not in sentence) # True
 

🔹 11. String Immutability

Strings are immutable → once created, they cannot be changed.

✅ Example:

name = "Sakshi"
# name[0] = 'R' ❌ Error
name = "Rakshi"   # ✅ New string created
 

🧠 Mini Practice Programs

  1. Count vowels and consonants in a string.
  2. Check if a string is palindrome (same forward & backward).
  3. Count how many times a character appears in a string.
  4. Convert a string to title case manually.
  5. Remove all spaces from a string.

💡 Example: Check Palindrome

s = input("Enter a string: ")
if s == s[::-1]:
   print("Palindrome")
else:
   print("Not Palindrome")