Hello Friends,
String Handling in Python
A string in Python is a sequence of characters enclosed within single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """). Strings are used to store and manipulate text data.
Creating Strings
name = "Python" message = 'Welcome to Python' paragraph = """Python is easy and powerful"""
Accessing Characters in a String
Strings are indexed starting from 0.
text = "Python" print(text[0]) print(text[3])
Output:
P h
String Slicing
Slicing is used to extract a portion of a string.
text = "Python Programming" print(text[0:6]) print(text[7:]) print(text[:6]) print(text[-11:])
Output:
Python Programming Python Programming
String Immutability
Strings are immutable, meaning they cannot be changed after creation.
text = "Python" text[0] = "J" # Error
Correct Way:
text = "Python" text = "J" + text[1:] print(text)
Common String Methods
Changing Case
text = "Python Programming" print(text.upper()) print(text.lower()) print(text.title())
Removing Whitespaces
text = " Python " print(text.strip()) print(text.lstrip()) print(text.rstrip())
Searching in Strings
text = "Python Programming"
print(text.find("Python"))
print(text.count("o"))
Replacing Text
text = "I like Java"
text = text.replace("Java", "Python")
print(text)
Checking String Content
text = "Python123" print(text.isalpha()) print(text.isdigit()) print(text.isalnum())
Splitting and Joining Strings
Split
text = "Python,Java,C++"
languages = text.split(",")
print(languages)
Join
languages = ["Python", "Java", "C++"] text = " | ".join(languages) print(text)
String Formatting
Using f-strings (Recommended)
name = "Chandan"
age = 36
print(f"My name is {name} and I am {age} years old")
Using format()
print("My name is {} and I am {} years old".format(name, age))
Iterating Over a String
text = "Python"
for char in text:
print(char)
String Comparison
a = "python" b = "Python" print(a == b) print(a.lower() == b.lower())
Real-Life Examples
Example 1: Validate Email
email = "test@gmail.com"
if "@" in email and "." in email:
print("Valid Email")
else:
print("Invalid Email")
Example 2: Count Words
text = "Python is easy to learn" words = text.split() print(len(words))
Common Mistakes
- Trying to modify a string directly
- Forgetting string methods return new strings
- Incorrect indexing
Summary
- Strings store text data
- Strings are immutable
- Python provides many built-in string methods
- f-strings are the best way for formatting
No comments:
Post a Comment