Strings
## Learning Objectives
- Master string creation and manipulation
- Understand string methods
- Learn slicing and formatting
- Work with regular expressions basics
## Creating Strings
### Basic Strings
```python
single = 'Hello'
double = "Hello"
multi = """This is a
multi-line string"""
# Escape characters
path = "C:\\Users\\Name"
newline = "Line 1\nLine 2"
tab = "Col1\tCol2"
```
### Raw Strings
```python
path = r"C:\Users\Name" # Backslashes not escaped
```
### f-strings (Python 3.6+)
```python
name = "Alice"
age = 30
print(f"My name is {name} and I'm {age}")
print(f"In 5 years: {age + 5}")
```
## String Slicing
```python
text = "Hello, World!"
print(text[0]) # H
print(text[-1]) # !
print(text[0:5]) # Hello
print(text[7:12]) # World
print(text[:5]) # Hello
print(text[7:]) # World!
print(text[::2]) # Hlo ol! (every other char)
print(text[::-1]) # !dlroW ,olleH (reverse)
```
## String Length
```python
text = "Hello"
print(len(text)) # 5
```
## String Methods
### Case Methods
```python
text = "Hello, World!"
print(text.upper()) # HELLO, WORLD!
print(text.lower()) # hello, world!
print(text.capitalize()) # Hello, world!
print(text.title()) # Hello, World!
print(text.swapcase()) # hELLO, wORLD!
```
### Search and Find
```python
text = "Hello, World!"
print(text.find("World")) # 7 (index of first match)
print(text.find("Python")) # -1 (not found)
print(text.index("World")) # 7 (raises if not found)
print(text.count("o")) # 2 (count occurrences)
print(text.startswith("Hello")) # True
print(text.endswith("!")) # True
```
### Strip and Clean
```python
text = " Hello "
print(text.strip()) # "Hello" (remove both ends)
print(text.lstrip()) # "Hello " (remove left)
print(text.rstrip()) # " Hello" (remove right)
# Strip specific characters
text = "...Hello..."
print(text.strip(".")) # "Hello"
```
### Split and Join
```python
text = "apple,banana,cherry"
print(text.split(",")) # ['apple', 'banana', 'cherry']
print(text.split(",", 1)) # ['apple', 'banana,cherry']
# Join
words = ["apple", "banana", "cherry"]
print(",".join(words)) # apple,banana,cherry
print(" ".join(words)) # apple banana cherry
print("\n".join(words)) # apple\nbanana\ncherry
```
### Replace
```python
text = "Hello, World!"
print(text.replace("World", "Python")) # Hello, Python!
print(text.replace("o", "0")) # Hell0, W0rld!
# Replace with count
print(text.replace("o", "0", 1)) # Hell0, World!
```
### Check Content
```python
text = "Hello123"
print(text.isalpha()) # False (has digits)
print(text.isdigit()) # False
print(text.isalnum()) # True (letters or digits)
print(text.isnumeric()) # False
num = "12345"
print(num.isdigit()) # True
print(num.isnumeric()) # True
mixed = "Hello World"
print(mixed.islower()) # False
print(mixed.isupper()) # False
print(mixed.istitle()) # True
print(mixed.isspace()) # False
```
## String Formatting
### f-strings (Recommended)
```python
name = "Alice"
age = 30
pi = 3.14159
print(f"Name: {name}, Age: {age}")
print(f"Pi: {pi:.2f}") # 3.14
print(f"Binary: {42:b}") # Binary: 101010
print(f"Hex: {255:02x}") # Hex: ff
```
### format() Method
```python
print("{} and {}".format("apple", "banana")) # apple and banana
print("{1} and {0}".format("apple", "banana")) # banana and apple
print("{name} is {age}".format(name="Alice", age=30))
print("{:>10}".format("right")) # " right"
print("{:10}".format("left")) # "left "
print("{:^10}".format("center")) # " center "
print("{:*>10}".format("pad")) # "********pad"
```
### % Operator
```python
name = "Alice"
score = 85.5
print("Hello, %s" % name) # Hello, Alice
print("%s scored %.1f" % (name, score)) # Alice scored 85.5
print("%d %f" % (42, 3.14)) # 42 3.140000
```
## String Concatenation
```python
# With +
first = "Hello"
second = "World"
print(first + ", " + second) # Hello, World
# With join
parts = ["Hello", "World"]
print(", ".join(parts)) # Hello, World
# With f-string
print(f"{first}, {second}") # Hello, World
# Repeat with *
print("Ha" * 3) # HaHaHa
```
## String Comparison
```python
print("apple" == "apple") # True
print("apple" == "Apple") # False
print("apple" < "banana") # True (alphabetical)
print("a" < "A") # False (ASCII)
```
## String to List and Back
```python
# String to list
text = "hello"
chars = list(text)
print(chars) # ['h', 'e', 'l', 'l', 'o']
# List to string
chars = ['h', 'e', 'l', 'l', 'o']
print("".join(chars)) # hello
```
## Immutable Nature
Strings are immutable - they cannot be changed in place:
```python
text = "Hello"
# text[0] = "J" # TypeError!
# Instead:
text = "J" + text[1:] # Creates new string
print(text) # Jello
```
## Common Patterns
### Check if String Contains Substring
```python
text = "Hello, World!"
if "World" in text:
print("Found!")
if "Python" not in text:
print("Not found")
```
### Remove Punctuation
```python
import string
text = "Hello, World! How are you?"
clean = text.translate(str.maketrans("", "", string.punctuation))
print(clean) # Hello World How are you
```
### Check if Number
```python
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
print(is_number("123")) # True
print(is_number("12.3")) # True
print(is_number("abc")) # False
```
## Summary
- Strings are immutable sequences of characters
- Use f-strings for formatting (Python 3.6+)
- Key methods: split(), join(), replace(), strip(), find(), upper(), lower()
- Slice with `[start:stop:step]`
- `in` checks for substring membership
- Strings support indexing and slicing
- Use `join()` to combine strings efficiently
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →