Master String Manipulation with Interactive Examples
Strings in Python can be created using single quotes, double quotes, or triple quotes:
# Single quotes
name = 'Alice'
# Double quotes
message = "Hello, World!"
# Triple quotes for multi-line strings
paragraph = """This is a
multi-line string that
spans several lines."""
Each character in a string has a position (index). Python uses zero-based indexing:
text = "Python"
print(text[0]) # 'P'
print(text[3]) # 'h'
text = "Python"
print(text[-1]) # 'n'
print(text[-3]) # 'h'
text = "Hello"
# text[0] = 'h' # This will cause an error!
# Instead, create a new string:
new_text = 'h' + text[1:] # 'hello'
\n # Newline
\t # Tab
\\ # Backslash
\' # Single quote
\" # Double quote
text = "Line 1\nLine 2"
path = "C:\\Users\\Documents"
quote = "She said \"Hi!\""
first = "Hello"
last = "World"
result = first + " " + last
# "Hello World"
laugh = "ha" * 3
# "hahaha"
separator = "-" * 20
# "--------------------"
Type Python string operations and see the results instantly. Try examples like:
"Hello".upper()
"WORLD".lower()
"Python"[0:3]
"ha" * 3
"Hello" + " World"
Visualize how string slicing works with positive and negative indices.
"Python"[0:3]
# "Pyt"
"Python"[2:]
# "thon"
"Python"[::-1]
# "nohtyP"
"Python"[::2]
# "Pto"
Explore common string methods with interactive examples.
The most modern and readable way to format strings:
name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old."
# With expressions
price = 19.99
result = f"Total: ${price * 2:.2f}" # "Total: $39.98"
The traditional formatting method:
# Positional arguments
message = "Hello, {}! You have {} messages.".format("Bob", 5)
# Named arguments
result = "Name: {name}, Score: {score}".format(name="Alice", score=95)
# With indices
text = "{0} loves {1} and {1} loves {0}".format("Alice", "Bob")
The legacy formatting method (still works but less preferred):
name = "Alice"
age = 25
message = "My name is %s and I am %d years old." % (name, age)
# With formatting
pi = 3.14159
result = "Pi is approximately %.2f" % pi # "Pi is approximately 3.14"
Test your understanding of Python strings!