2.3 Strings
Exploring strings (str) for representing text. We will see how they are created, basic operations like concatenation and repetition, as well as advanced techniques like indexing, slicing, and using f-strings.
Strings (`str`) are sequences of characters used to represent text. In Python, strings can be delimited by either single (') or double (") quotes. For text that spans multiple lines, triple quotes (either `"""` or `'''`) are used. A key feature of strings is that they are immutable, meaning you cannot change their content after they are created. Any operation that appears to modify them actually creates a new string.
Creation and Basic Operations
# Creating strings
message_single_quotes = 'This is a string.'
message_double_quotes = "This is also a string. Using different quotes allows embedding the other type, e.g., 'this'."
# Multi-line strings
multiline_text = """This is text
that spans
multiple lines."""
print(multiline_text)
print("-" * 20)
# Concatenation (+) and Repetition (*)
first_name = "Alexander"
last_name = "Papas"
full_name = first_name + " " + last_name
print(f"Concatenation: {full_name}")
separator_line = "=" * 20
print(f"Repetition: {separator_line}")
# String length with the len() function
print(f"The length of the name '{first_name}' is: {len(first_name)}")
Indexing and Slicing: Accessing Characters
Because strings are sequences, you can access individual characters using their index in square brackets `[]`. Indexing starts at 0. Slicing allows you to extract a "piece" of the string by defining the start, end, and step.
word = "Programming"
print(f"The word is: {word}")
print(f"First character (index 0): {word[0]}")
print(f"Fifth character (index 4): {word[4]}")
print(f"Last character (index -1): {word[-1]}")
print(f"Second to last character (index -2): {word[-2]}")
print("-" * 20)
# Slicing: string[start:stop:step]
print(f"The first 5 characters (indices 0-4): {word[0:5]} or simply {word[:5]}")
print(f"From the 6th character (index 5) to the end: {word[5:]}")
print(f"From the 3rd (index 2) to the 8th (index 7): {word[2:8]}")
print(f"Reverse the word: {word[::-1]}")
print(f"Every second character: {word[::2]}")
String Methods and Formatting with F-strings
Python strings come with a multitude of built-in methods that perform useful operations. F-strings (formatted string literals), introduced in Python 3.6, are the most modern and readable way to embed variables and expressions directly into strings.
text = " Hello World! "
print(f"Original text: '{text}'")
# Conversion and cleaning
print(f"Uppercase: '{text.upper()}'")
print(f"Lowercase: '{text.lower()}'")
print(f"Removing whitespace (start/end) with strip(): '{text.strip()}'")
# Content checking
print(f"Starts with ' H': {text.startswith(' H')}")
print(f"Ends with '!': {text.strip().endswith('!')}")
# Replacement and splitting
new_text = text.strip().replace("World", "Python")
print(f"With replacement: '{new_text}'")
words = new_text.split(" ")
print(f"Split into a list: {words}")
# F-string for dynamic text creation
name = "Maria"
age = 28
print(f"{name.upper()} is {age} years old. In 5 years, she will be {age + 5}.")
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.