Python String Manipulation Fundamentals
Python Strings Basics
What is a String?
In programming, we need a way to work with text. A string is how we do that. It's simply a sequence of characters, like letters, numbers, and symbols, put together.
String
noun
A data type used to represent text, made up of a sequence of characters.
Think of a friendship bracelet with letter beads. Each bead is a character. When you line them up, you get a word or a sentence. That's a string. The whole sequence—'H', 'e', 'l', 'l', 'o'—forms the string "Hello".
Ways to Define a String
In Python, you can create strings using single quotes ('), double quotes ("), or triple quotes (''' or """). The program treats them all the same. The flexibility is for our convenience.
my_string_1 = 'This is a string.'
my_string_2 = "This is also a string."
So why have different options? It helps when your string itself needs to contain a quote. If you need an apostrophe (which is a single quote), you can wrap the whole string in double quotes.
This avoids confusing Python about where the string ends.
# This works because the outer quotes are different
# from the inner one.
quote = "It's a sunny day."
print(quote)
Triple quotes are special. They let you create strings that span multiple lines. This is useful for long blocks of text, like a paragraph or a poem.
multi_line_string = '''
This is the first line.
This is the second line.
And this is the third.
'''
print(multi_line_string)
The Rules of the String
Strings have one very important rule: they are immutable. This is a key concept in Python. means that once a string is created, it can never be changed.
Think of it like a published book. If you find a typo on page 50, you can't just erase the ink and write over it. The page is already printed. To fix the error, you have to create a whole new, corrected edition of the book.
Strings work the same way. You can't change a single character within an existing string. If you want to alter a string, Python creates a brand new one with your changes.
This is why string operations, like combining two strings, always result in a new string.
Let's see an example. If you try to change the first letter of a string, Python will give you an error.
name = "Sam"
# Let's try to change 'S' to 'P'
name[0] = 'P' # This will cause an error!
The code above fails because we tried to modify an immutable object. To change "Sam" to "Pam", you must create an entirely new string.
name = "Sam"
# Create a new string with the desired change
new_name = 'P' + name[1:] # We'll cover this kind of operation later
print(new_name)
# The original 'name' string is unchanged
print(name)
Understanding immutability is fundamental. It explains the behavior of every string function you'll learn later on. They don't change strings; they return new ones.
In programming, what is the best definition of a string?
What does it mean for a string to be "immutable" in Python?
