Day 7: Strings in Python (Complete Guide)
Strings are one of the most powerful and frequently used data types in Python. From handling user input to building AI systems, strings are everywhere. Mastering them is non-negotiable if you want to become strong in programming.
What is a String?
A string is a sequence of characters enclosed in quotes.
name = "Piyush"
city = 'Pune'
message = """Multi-line string"""
String Indexing
Each character has a position (index).
text = "Python"
print(text[0]) # P
print(text[5]) # n
Index starts from 0
Negative Indexing
text = "Python"
print(text[-1]) # n
print(text[-2]) # o
Access from the end
String Slicing
Extract parts of a string.
text = "Python Programming"
print(text[0:6]) # Python
print(text[7:]) # Programming
print(text[:6]) # Python
print(text[::2]) # Pto rgamn
String Immutability
Strings cannot be changed after creation.
text = "hello"
# text[0] = "H" ❌ Error
✔ Correct approach:
text = "hello"
text = "H" + text[1:]
Important String Methods
Case Conversion
text = "python"
print(text.upper()) # PYTHON
print(text.lower()) # python
print(text.title()) # Python
Searching
text = "hello world"
print(text.find("world")) # 6
print(text.count("l")) # 3
Replace
text = "I like Java"
print(text.replace("Java", "Python"))
Strip Spaces
text = " hello "
print(text.strip())
Split & Join
text = "apple,banana,mango"
fruits = text.split(",")
print(fruits)
print("-".join(fruits))
String Concatenation
print("Hello" + " " + "World")
String Formatting (Best Practice)
name = "Piyush"
age = 21
print(f"My name is {name} and I am {age} years old")
Escape Characters
print("Hello\nWorld")
print("Hello\tWorld")
print("He said \"Python is awesome\"")
Membership Operators
text = "Python"
print("Py" in text) # True
print("Java" not in text) # True
Notes (Important)
- Strings are immutable
- Indexing starts from 0
- Strings are iterable
- Slicing is safe (no error if out of range)
- Prefer f-strings for formatting
Practice Questions
Basic
- Print first and last character of a string
- Reverse a string using slicing
- Count total characters in a string
- Convert string to uppercase and lowercase
Intermediate
- Check if a string is palindrome
- Count vowels and consonants
- Remove spaces from a string
- Find frequency of each character
Advanced
- Check if two strings are anagrams
- Find the longest word in a sentence
- Implement your own replace() function
- Compress a string (e.g., "aaabb" → "a3b2")
.png)

0 Comments:
Post a Comment