Strings are sequences of characters, used for handling text data. They are immutable, meaning once created, they cannot be changed directly. Python provides many built-in methods for working with strings.
👉 Essential for almost any program that interacts with text, from usernames to file paths.
🔹 1. What is a String?
A string is a sequence of characters, enclosed in single quotes
'', double quotes "", or triple quotes """ """ for multi-line strings.Example:
name = "Pythonista"
message = 'Hello, world!'
multiline = """This is
a multi-line
string."""
print(name)
Output:
Pythonista🔹 2. Accessing Characters (Indexing & Slicing)
• Indexing: Get a single character using its position (index starts at
0).• Slicing: Get a sub-sequence of characters (a "slice") using
[start:end]. The end index is exclusive.Example:
word = "developer"
print(word[0]) # First character
print(word[3:7]) # Characters from index 3 up to (but not including) 7
print(word[-1]) # Last character
Output:
delopr🔹 3. String Concatenation & Length
• Concatenation: Joining strings using the
+ operator.•
len() function: Returns the number of characters in a string.Example:
first = "Hello"
last = "World"
full_message = first + " " + last + "!"
print(full_message)
print(len(full_message))
Output:
Hello World!12🔹 4. Common String Methods
•
.upper() / .lower(): Convert to uppercase/lowercase.•
.strip(): Removes leading/trailing whitespace.•
.replace(old, new): Replaces occurrences of a substring.•
.split(delimiter): Splits the string into a list of substrings.Example:
text = " Hello Python! "
print(text.strip())
print("apple,banana,cherry".split(','))
print("Python".replace('o', '0'))
Output:
Hello Python!['apple', 'banana', 'cherry']Pyth0n🔹 5. F-strings (Formatted String Literals)
A powerful and easy way to embed expressions inside string literals. Prefix the string with
f or F.Example:
item = "book"
price = 19.99
print(f"The {item} costs ${price:.2f}.") # .2f for 2 decimal places
Output:
The book costs $19.99.🎯 Today's Goal(What you should do)
✔️ Understand string immutability
✔️ Access characters and slice strings
✔️ Use common string methods for manipulation
✔️ Format strings with f-strings