► Understanding Strings
Strings are sequences of characters used to represent text in programming. They’re one of the most commonly used data types, essential for handling any text-based information like names, messages, or user input.
► Real-World Analogy
Think of strings like a sentence in a book:
» Each character is like a letter on the page
» You can read from left to right (iterate through string)
» You can highlight a specific word (substring)
» You can change uppercase to lowercase (case conversion)
» You can count the words or letters (length)
» You can join sentences together or split them apart
► Key Concepts
✓ Immutable: Strings cannot be changed after creation
✓ Indexed: Access individual characters by position
✓ Concatenation: Combine strings using + operator
✓ Methods: Built-in functions for string manipulation
✓ Escape sequences: Special characters like \n (newline)
■ Code Examples
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# Creating strings name = "Alice" greeting = 'Hello, World!' multi_line = """This is a multi-line string""" print(greeting) print(f"Length: {len(name)}") # String concatenation first = "Hello" last = "World" full = first + " " + last print(full) # String methods text = "python programming" print(f"Uppercase: {text.upper()}") print(f"Capitalize: {text.capitalize()}") print(f"Replace: {text.replace('python', 'Python')}") print(f"Split: {text.split()}") # String slicing word = "Programming" print(f"First 4 chars: {word[:4]}") print(f"Last 4 chars: {word[-4:]}") print(f"Reverse: {word[::-1]}") |
