Working with Strings
Introduction to Strings
In Python, a string is a sequence of characters. Unlike numbers, strings are used to represent text. They are created by enclosing characters in single quotes (') or double quotes ("). Python stores strings as a sequence where each character has a specific position called an index.
Pythonmy_string = 'Hello World' # Both work the same another = "Python is fun"
Basic Operations: Indexing & Slicing
Indexing starts at 0. You can access individual characters using square brackets. Slicing allows you to get a sub-string by specifying a range [start:end]. Negative indices count from the end of the string.
Pythonname = "Python" print(name[0]) # 'P' print(name[-1]) # 'n' (last char) print(name[1:4]) # 'yth' (index 1 up to but NOT including 4)
Concatenation & Repetition
You can combine strings using the plus (+) operator (concatenation) and repeat them using the asterisk (*) operator.
Pythongreet = "Hello" + " " + "World" laugh = "ha" * 3 # "hahaha"
Powerful String Methods
Python provides many built-in methods to transform text. Methods like .upper(), .lower(), .strip() (removes whitespace), and .replace() are commonly used to clean data.
Pythontext = " Python " print(text.strip().upper()) # "PYTHON" print("apple-banana".split("-")) # ['apple', 'banana']
Searching & Matching
Use the 'in' keyword to check if a substring exists. The .find() method returns the index of the first occurrence, and .count() tell you how many times a substring appears.
Pythonmsg = "Learning Python is great" print("Python" in msg) # True print(msg.count("e")) # 2
Formatting with f-strings
Modern Python uses f-strings for readability. Just prefix the string with 'f' and use curly braces {} to inject variables directly into the text.
Pythonname = "Alex" score = 95 print(f"User {name} scored {score} points.")
Escape Characters & Raw Strings
Special characters like newlines (\n) or tabs (\t) use backslashes. If you want backslashes to be treated literally (like in file paths), use a raw string by prefixing it with 'r'.
Pythonprint("Line 1\nLine 2") path = r"C:\Users\Documents"
String Immutability
A key rule in Python: Strings are immutable. This means once a string is created, you cannot change its individual characters. Any 'change' actually creates a whole new string in memory.
Pythontext = "Python" # text[0] = 'J' # This would cause an ERROR text = "J" + text[1:] # This works (creates new string)
Intermediate: Regex and Encoding
For complex pattern matching (like validating emails), Python uses the 're' module for Regular Expressions. Additionally, computers represent characters using encodings like UTF-8.
Pythonimport re # Simple regex example (matches 3 digits) print(re.findall(r'\d{3}', "Order ID: 123")) # ['123']
Master this concept
Hands-on practice is the fastest way to learn. Head over to our interactive workspace to solve this topic's challenge.