String manipulation
Advanced text operations
Strings are sequences of characters. You'll use them all the time in your Python projects. Let's learn how to work with them!
Working with text
Python treats text as strings. You define a string using single quotes or double quotes.
my_string = "Hello, World!"
another_string = 'Python is fun.'String operations
You can do many things with strings. Two basic operations are joining them together and repeating them.
Concatenation (joining)
The simplest way to combine two strings is with the + operator. This is called concatenation.
first_name = "Ada"
last_name = "Lovelace"
full_name = first_name + " " + last_name
print(full_name) # Output: Ada LovelaceRepetition
You can repeat a string using the * operator and an integer. The string will be repeated that many times.
cheer = "Hip " * 2 + "Hooray!"
print(cheer) # Output: Hip Hip Hooray!
separator = "-" * 10
print(separator) # Output: ----------String methods
Strings in Python come with many built-in functions called methods. These methods help you perform common tasks on your text data.
Changing case
You can easily change the case of characters in a string.
upper(): Converts all characters to uppercase.lower(): Converts all characters to lowercase.capitalize(): Makes the first character uppercase and the rest lowercase.
message = "hello World"
print(message.upper()) # Output: HELLO WORLD
print(message.lower()) # Output: hello world
print(message.capitalize()) # Output: Hello worldCleaning strings
Sometimes strings have extra spaces or unwanted characters. The strip() method can help.
strip(): Removes whitespace from both the beginning and the end.lstrip(): Removes whitespace from the left (beginning).rstrip(): Removes whitespace from the right (end).
user_input = " Python rocks! \n"
clean_input = user_input.strip()
print(f"'{clean_input}'") # Output: 'Python rocks!'
prompt = ">>> "
print(f"'{prompt.rstrip()}'") # Output: '>>>'Finding and replacing
You can search for specific text within a string or replace parts of it.
find('substring'): Returns the starting index of the first occurrence of the substring. Returns-1if not found.replace('old', 'new'): Replaces all occurrences of the 'old' substring with 'new'.
sentence = "I love Python, Python is great!"
index = sentence.find("Python")
print(f"'Python' starts at index {index}") # Output: 'Python' starts at index 7
new_sentence = sentence.replace("Python", "programming")
print(new_sentence) # Output: I love programming, programming is great!Common mistakes
Don't forget that strings are immutable. This means string methods create a *new* string. They don't change the original one.
my_str = "Hello"
my_str.upper() # This does nothing useful!
print(my_str) # Output: Hello (still unchanged)
# You need to assign the result to a variable:
updated_str = my_str.upper()
print(updated_str) # Output: HELLOPractice
Try these exercises to lock in what you just learned.
1word = "python"2
What's next?
You've learned the basics of string manipulation! Strings are incredibly versatile. Next, you'll learn f-strings, the easiest way to put variables inside text, and then how to grab pieces of a string with indexing and slicing.