Strings and Multiline Strings
Strings and Multiline Strings
Examples:
name = "Alice"
message = 'Hello, world!'
address = '''123 Main Street
New York, NY'''
Key Properties:
2. String Operations
3. String Methods
"a,b,c".split(",") →
.split() Splits into a list of substrings ["a","b","c"]
.find()
Returns the first index of a "apple".find("p") → 1
substring
.replace()
Replaces a substring with "hello".replace("e", "a") →
another "hallo"
Important Notes:
.find() vs .index():
4. String Formatting
2. Formatting Numbers:
3. Alignment:
print(f"{'Left':<10}") # Left-aligned: "Left "
print(f"{'Right':>10}") # Right-aligned: " Right"
5. Escape Characters
Escap
Meaning Example
e
\n Newline "Line1\nLine2"
\t Tab "Hello\tWorld"
\\ Backslash "C:\\Users"
Example:
print("Hello\nWorld")
# Output:
# Hello
# World
6. Multiline Strings
Use triple quotes (''' or """) for multiline strings:
Use Cases:
7. Common Mistakes
1. Forgetting Quotes:
message = Hello # SyntaxError: Missing quotes.
2. Mismatched Quotes:
text = 'He said "Wow!' # Missing closing quote.
3. Unescaped Quotes:
text = "She said "Hello"" # Error: Use \" or different quotes.
4. Useless f-strings:
print(f"Hello") # Works but unnecessary (no variables embedded).
8. Real-World Applications
3. Generating Reports:
header = "Name".ljust(15) + "Age".rjust(5)
print(header) # Output: "Name Age"
9. Practice Examples
3. Reverse a String:
text = "Python"
reversed_text = text[::-1]
print(reversed_text) # Output: "nohtyP"
Key Takeaways