🧵 Strings in Python (Lecture 8)
YouTube Reference: Watch Lecture
🔤 What is a String?
A string is a sequence of characters enclosed in single (' '), double (" "), or
triple (''' or """) quotes.
Strings are immutable, meaning once created, their content cannot be changed.
s1 = 'Hello'
s2 = "World"
s3 = """Multiline
String"""
✂️String Slicing & Indexing
s = "Python"
print(s[0]) # 'P'
print(s[-1]) # 'n'
print(s[1:4]) # 'yth'
print(s[:3]) # 'Pyt'
print(s[3:]) # 'hon'
print(s[::-1]) # 'nohtyP' (reversed string)
Syntax: string[start:stop:step]
🧰 Most Useful String Methods
s = " Hello, Python! "
s.lower() # ' hello, python! '
s.upper() # ' HELLO, PYTHON! '
s.strip() # 'Hello, Python!' (removes leading & trailing spaces)
s.lstrip() # removes only leading spaces
s.rstrip() # removes only trailing spaces
s.replace("Python", "World") # ' Hello, World! '
s.split(",") # [' Hello', ' Python! ']
s.find("Python") # 9 (starting index), -1 if not found
s.count("o") #2
len(s) # 17 (includes spaces)
"{} is {}".format("Python", "awesome") # 'Python is awesome'
f"{s} is awesome" # f-strings for formatting
🔁 String and List Conversion
String ➜ List
sentence = "apple banana cherry"
words = sentence.split() # ['apple', 'banana', 'cherry']
List ➜ String
words = ['one', 'two', 'three']
text = " ".join(words) # 'one two three'
Joining without space:
chars = ['H', 'e', 'y']
"".join(chars) # 'Hey'
✅ Boolean Nature of Strings
Any non-empty string is True
Empty string ("") is False
bool("hello") # True
bool("") # False
❓ Common Questions on Strings
🔹 Check for Palindrome
s = "madam"
print(s == s[::-1]) # True
🔹 Count Vowels in a String
vowels = "aeiou"
s = "education"
count = sum(1 for ch in s if ch.lower() in vowels) # 5
🔹 Remove Duplicates While Preserving Order
s = "banana"
print("".join(dict.fromkeys(s))) # 'ban'
🔹 Check Anagram
s1 = "listen"
s2 = "silent"
print(sorted(s1) == sorted(s2)) # True
🔹 Reverse Each Word in a String
s = "hello world"
" ".join(word[::-1] for word in s.split()) # 'olleh dlrow'
🔹 Reverse Word Order
s = "life is beautiful"
" ".join(s.split()[::-1]) # 'beautiful is life'
💬 Escape Characters in Strings
Escape Meaning
\n New Line
\t Tab Space
\' Single Quote
\" Double Quote
\\ Backslash