Strings
Strings are an essential data type in Python, used to represent text data. They are sequences of characters enclosed within single (') or double (") quotes.
message = "Hello, World!"
alternative = 'Python is fun!'
An empty string is simply "" or '', containing zero characters.
Basic String Operations
Concatenation
Combine strings using the + operator:
greeting = "Hello, " + "Alice!"
print(greeting) # Output: Hello, Alice!
Repetition
Repeat strings using the * operator:
laugh = "Ha" * 3
print(laugh) # Output: HaHaHa
Length
Find the length of a string using the len() function:
length = len("Python")
print(length) # Output: 6
String Indexing and Slicing
Strings are immutable sequences of characters, meaning individual characters cannot be changed after the string is created. However, you can access and manipulate parts of strings.
Accessing Characters
- Zero-Based Indexing: The first character is at index
0.
fruit = "Banana"
print(fruit[0]) # Output: 'B'
print(fruit[3]) # Output: 'a'
- Negative Indexing: Access characters from the end using negative indices.
print(fruit[-1]) # Output: 'a' (last character)
print(fruit[-3]) # Output: 'a'
Slicing Strings
Extract substrings using the slice syntax string[start:end]:
print(fruit[0:3]) # Output: 'Ban' (characters at indices 0,1,2)
print(fruit[2:]) # Output: 'nana' (from index 2 to end)
print(fruit[:4]) # Output: 'Bana' (from start to index 3)
- Slice Parameters:
start: Starting index (inclusive). Defaults to0if omitted.end: Ending index (exclusive). Defaults tolen(string)if omitted.
Examples
text = "Mangosteen"
print(text[1:4]) # Output: 'ang'
print(text[:5]) # Output: 'Mango'
print(text[5:]) # Output: 'steen'
Modifying Strings
While strings are immutable, you can create new strings based on existing ones.
Creating New Strings
message = "Hello, worzd!"
# Incorrect character at index 10 ('z')
# Cannot do: message[10] = 'l' # Raises TypeError
# Correct approach:
new_message = message[:10] + 'l' + message[11:]
print(new_message) # Output: 'Hello, world!'
Finding Substrings
Use the index() method to find the position of a substring:
print("winter".index("t")) # Output: 3
print("winter".index("ter")) # Output: 3
- Note: If the substring is not found,
index()raises aValueError.
Checking Substring Presence
Use the in keyword:
print("Dragons" in "Mythical creatures") # Output: False
print("cat" in "concatenate") # Output: True
String Methods
Python provides numerous methods for string manipulation.
Transforming Strings
upper() And lower()
Convert strings to uppercase or lowercase:
name = "Alice"
print(name.upper()) # Output: 'ALICE'
print(name.lower()) # Output: 'alice'
strip(), lstrip(), rstrip()
Remove whitespace:
text = " Hello, World! "
print(text.strip()) # Output: 'Hello, World!'
print(text.lstrip()) # Output: 'Hello, World! '
print(text.rstrip()) # Output: ' Hello, World!'
Analyzing Strings
count(substring)
Count occurrences of a substring:
print("banana".count("a")) # Output: 3
endswith(substring)
Check if a string ends with a given substring:
filename = "report.pdf"
print(filename.endswith(".pdf")) # Output: True