4 of 20 topics completed
Python Strings and String Manipulation
Strings are one of the most commonly used data types in programming. In this tutorial, you'll learn how to create, format, and manipulate text in Python with easy-to-understand examples.
What are Strings?
A string is simply a sequence of characters. Think of your favorite quote, a message to a friend, or even this sentence you're reading - all of these are strings!
💡 Real-World Example
Strings are everywhere in real applications - from the username you type when logging into a website, to the text in this tutorial, to the messages in your favorite chat app.
Creating Strings in Python
In Python, you can create strings by enclosing text in single quotes ('), double quotes ("), or triple quotes (''' or """) for multi-line strings.
1# Different ways to create strings2name = 'Alice'3message = "Hello, Python learner!"4address = '''123 Coding Street5Pythonville, PY 12345'''67print(name)8print(message)9print(address)
String Operations
1. Concatenation (Combining Strings)
You can join strings together using the + operator:
1first_name = "John"2last_name = "Doe"34# Joining strings with +5full_name = first_name + " " + last_name6print(full_name) # Output: John Doe78# Creating a greeting9greeting = "Hello, " + full_name + "!"10print(greeting) # Output: Hello, John Doe!
2. String Repetition
You can repeat a string multiple times using the * operator:
1# Repeating strings2stars = "*" * 103print(stars) # Output: **********45cheer = "Hip Hip Hooray! " * 36print(cheer) # Output: Hip Hip Hooray! Hip Hip Hooray! Hip Hip Hooray!
String Methods
Python provides many built-in methods to manipulate strings. Here are some of the most useful ones:
Changing Case
text = "Python Programming"# Convert to uppercaseprint(text.upper()) # PYTHON PROGRAMMING# Convert to lowercaseprint(text.lower()) # python programming# Capitalize first letterprint(text.capitalize()) # Python programming
Finding & Replacing
message = "Hello, World!"# Find position of a substringprint(message.find("World")) # 7# Replace part of a stringnew_message = message.replace("World", "Python")print(new_message) # Hello, Python!
Checking Content
password = "Secure123"# Check if string starts withprint(password.startswith("Sec")) # True# Check if string ends withprint(password.endswith("!")) # False# Check if all characters are alphanumericprint(password.isalnum()) # True# Check if all characters are digitsprint(password.isdigit()) # False
Trimming & Splitting
text = " Python is fun! "# Remove whitespace from start/endprint(text.strip()) # "Python is fun!"# Split string into a listwords = "apple,banana,orange".split(",")print(words) # ['apple', 'banana', 'orange']# Join list elements into a stringprint(" - ".join(words)) # apple - banana - orange
String Formatting
Python offers several ways to format strings. Let's explore them:
1. F-Strings (Recommended for modern Python)
1name = "Emma"2age = 253gpa = 3.945# f-strings (Python 3.6+)6info = f"Name: {name}, Age: {age}, GPA: {gpa:.1f}"7print(info) # Output: Name: Emma, Age: 25, GPA: 3.9
2. String format() Method
1# format() method2info = "Name: {}, Age: {}, GPA: {:.1f}".format(name, age, gpa)3print(info) # Output: Name: Emma, Age: 25, GPA: 3.945# Using numbered positions6message = "{0} is {1} years old. {0} has a GPA of {2:.1f}.".format(name, age, gpa)7print(message) # Output: Emma is 25 years old. Emma has a GPA of 3.9.
3. %-formatting (Older style)
1# %-formatting (older style)2info = "Name: %s, Age: %d, GPA: %.1f" % (name, age, gpa)3print(info) # Output: Name: Emma, Age: 25, GPA: 3.9
String Indexing and Slicing
You can access individual characters or parts of a string using indexing and slicing:
Index positions in the string "Python":
1text = "Python"23# Accessing individual characters4print(text[0]) # P (first character)5print(text[1]) # y (second character)6print(text[-1]) # n (last character)78# Slicing (getting a portion of the string)9print(text[0:2]) # Py (from index 0 up to but not including 2)10print(text[2:6]) # thon (from index 2 up to 6)11print(text[:3]) # Pyt (from start up to but not including 3)12print(text[3:]) # hon (from index 3 to the end)13print(text[-3:]) # hon (last 3 characters)14print(text[::2]) # Pto (every second character)
Practice Exercise: Building a Username Generator
Let's create a simple program that generates usernames from a person's name and some random numbers:
1import random23def generate_username(name):4 # Convert to lowercase5 name = name.lower()67 # Remove spaces8 name = name.replace(" ", "")910 # Take first 5 characters (or fewer if name is shorter)11 short_name = name[:5]1213 # Generate random number between 100 and 99914 random_num = random.randint(100, 999)1516 # Create username17 username = short_name + str(random_num)1819 return username2021# Test with different names22print(generate_username("John Smith")) # johns12323print(generate_username("Maria Garcia")) # maria45624print(generate_username("Li")) # li789
🎯 Try it yourself!
Extend the username generator with these challenges:
- Add an option to include special characters
- Create a function that validates if a username is acceptable (e.g., minimum length)
- Generate an email address using the username
String Methods Reference
Method | Description | Example |
---|---|---|
upper() | Converts to uppercase | "hello".upper() → "HELLO" |
lower() | Converts to lowercase | "HELLO".lower() → "hello" |
strip() | Removes whitespace from start/end | " hi ".strip() → "hi" |
replace() | Replaces occurrences of a substring | "hello".replace("l", "L") → "heLLo" |
split() | Splits string into a list | "a,b,c".split(",") → ["a", "b", "c"] |
join() | Joins list elements into a string | "-".join(["a", "b", "c"]) → "a-b-c" |
Related Tutorials
Learn about different types of data and how to store them in Python.
Learn moreUnderstand how to work with collections of items in Python.
Learn moreLearn to interact with users and display information.
Learn more