Strings Manipulation
Words as Data
Imagine you’re a hacker intercepting a message. It’s not numbers or code but text. Words, sentences, symbols. In Python, these are stored as strings. Strings are more than just text; they’re data structures that let you manipulate language, format output, and even encode information.
This chapter is about learning how to bend words to your will: slicing them, transforming them, and presenting them elegantly. Strings are the bridge between humans and machines so master them, and your programs will speak fluently.
Why Strings Matter
- Strings as Communication: Programs often interact with humans through text. Strings are the medium.
- Immutability: Strings in Python cannot be changed directly. Every modification creates a new string. This ensures consistency but requires careful handling.
- Manipulation: Slicing, concatenation, and methods allow you to reshape text.
- Formatting: Presenting data clearly is as important as computing it. Formatting strings makes output readable and professional.
String Basics
message = "Hello, Hacker!"
print(message)
- Why? Strings store text data. They’re enclosed in quotes (
' 'or" ").
Indexing: Strings are sequences, so each character has a position.
print(message[0]) # H
print(message[-1]) # !
String Manipulation
- Why? Combine strings to build new messages.
- Why? Extract parts of strings for analysis or transformation.
- Why? Built‑in methods simplify common transformations.
Methods:
word = "hackpods"
print(word.upper()) # HACKPODS
print(word.capitalize()) # Hackpods
print(word.replace("pods", "labs")) # hacklabs
Slicing:
text = "Python"
print(text[0:3]) # Pyt
print(text[2:]) # thon
Concatenation:
first = "Happy"
second = "Engineer"
print(first + " " + second)
String Formatting
Why? f‑strings are concise, readable, and powerful.
f‑Strings (Python 3.6+):
print(f"My name is {name} and I am {age} years old.")
format() Method:
age = 25
print("My name is {} and I am {} years old.".format(name, age))
Concatenation with Variables:
name = "Shubham"
print("Hello " + name)
Advanced String Tricks
Stripping Whitespace:
messy = " data "
print(messy.strip()) # data
Splitting & Joining:
sentence = "Python is fun"
words = sentence.split()
print(words) # ['Python', 'is', 'fun']
print("-".join(words)) # Python-is-fun
Checking Membership:
if "Hack" in "Happy Hacker":
print("Found!")
The Hacker’s Notebook
- Strings are immutable and every change creates a new one. Hackers plan transformations carefully. Indexing and slicing let you dissect text like a surgeon.
- Methods (
upper,replace,strip) are shortcuts for common manipulations. Formatting (format, f‑strings) makes output professional and readable.
Hacker’s Mindset: treat strings as your communication channel. Master manipulation, and your programs will not just compute but they’ll speak.
