String Manipulation in Python

 

What is String Manipulation? 

String manipulation is the art of modifying, slicing, and playing around with text in Python. Think of it as using a magic wand  to transform words into whatever you need!

Why Manipulate Strings?

  • Clean and format text 
  • Extract useful information 
  • Make code more efficient and readable 

Creating and Accessing Strings

Strings in Python are written inside quotes ("" or '').

text = "Hello, Python!"
print(text)  # Outputs: Hello, Python!

Accessing Characters 

Use indexing to get specific characters.

print(text[0])  # Outputs: H
print(text[-1])  # Outputs: !

String Slicing 

Want only a part of a string? Use slicing!

print(text[0:5])  # Outputs: Hello
print(text[:6])   # Outputs: Hello,
print(text[7:])   # Outputs: Python!

Modifying Strings

Strings are immutable, but we can create new modified versions.

Convert to Uppercase/Lowercase 

print(text.upper())  # Outputs: HELLO, PYTHON!
print(text.lower())  # Outputs: hello, python!

Remove Whitespace 

text = "   Python Magic   "
print(text.strip())  # Outputs: Python Magic

Replace Text 

print(text.replace("Python", "Code"))  # Outputs: Code Magic

String Concatenation and Formatting 

Combining Strings ➕

greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!"
print(message)  # Outputs: Hello, Alice!

Using f-strings 

age = 25
print(f"{name} is {age} years old.")  # Outputs: Alice is 25 years old.

Finding and Checking Strings 

Check if a word exists

print("Python" in text)  # Outputs: True

Find Position of a Substring

print(text.find("Magic"))  # Outputs: 7

Summary 

Concept Description
String Sequence of characters inside quotes
Indexing Access individual characters using indexes
Slicing Extract part of a string using [start:end]
Methods .upper(), .lower(), .strip(), .replace()
Concatenation Combine strings using + or f-strings


Post a Comment

0 Comments