A string is a sequence of characters enclosed in quotes. Strings are immutable, meaning once created, they cannot be changed. Strings support indexing, slicing, and a rich set of built-in methods for manipulation.
s = "hello"
s2 = 'world'
s3 = """multi
line"""
1. Access Characters
print(s[0]) # 'h'
print(s[-1]) # 'o' (last character)
2. Slicing
print(s[1:4]) # 'ell'
print(s[:3]) # 'hel'
print(s[::-1]) # 'olleh' (reverse string)
3. Concatenation
s = "hello"
s += " world"
print(s) # 'hello world'
4. Repetition
print("ha" * 3) # 'hahaha'
5. Length
print(len(s)) # Number of characters
6. Iteration
for char in s:
print(char)
7. Search
"ell" in s # True
s.find("l") # Returns 2 (first occurrence)
s.rfind("l") # Returns 3 (last occurrence)
s.index("l") # Like find(), but raises error if not found
8. Modification (via new string)
s = s.replace("world", "there") # 'hello there'
s.upper() # 'HELLO THERE'
s.lower() # 'hello there'
" hello ".strip() # 'hello'
"hello\n".rstrip() # 'hello'
9. Splitting and Joining
words = s.split() # ['hello', 'there']
joined = "-".join(words) # 'hello-there'
10. Formatting
name = "Ortie"
f"Hello, {name}!" # 'Hello, Ortie!'
"Hello, %s!" % name
str.format()
"Hello, {}!".format(name)
11. String Comparison
"apple" < "banana" # True (lexicographical)
12. Useful String Methods
s.isalpha() # All letters?
s.isdigit() # All digits?
s.startswith("he") # True
s.endswith("e") # True