Progress0%

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.

Python
1# Different ways to create strings
2name = 'Alice'
3message = "Hello, Python learner!"
4address = '''123 Coding Street
5Pythonville, PY 12345'''
6
7print(name)
8print(message)
9print(address)

String Operations

1. Concatenation (Combining Strings)

You can join strings together using the + operator:

Python
1first_name = "John"
2last_name = "Doe"
3
4# Joining strings with +
5full_name = first_name + " " + last_name
6print(full_name) # Output: John Doe
7
8# Creating a greeting
9greeting = "Hello, " + full_name + "!"
10print(greeting) # Output: Hello, John Doe!

2. String Repetition

You can repeat a string multiple times using the * operator:

Python
1# Repeating strings
2stars = "*" * 10
3print(stars) # Output: **********
4
5cheer = "Hip Hip Hooray! " * 3
6print(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

Python
text = "Python Programming"
# Convert to uppercase
print(text.upper()) # PYTHON PROGRAMMING
# Convert to lowercase
print(text.lower()) # python programming
# Capitalize first letter
print(text.capitalize()) # Python programming

Finding & Replacing

Python
message = "Hello, World!"
# Find position of a substring
print(message.find("World")) # 7
# Replace part of a string
new_message = message.replace("World", "Python")
print(new_message) # Hello, Python!

Checking Content

Python
password = "Secure123"
# Check if string starts with
print(password.startswith("Sec")) # True
# Check if string ends with
print(password.endswith("!")) # False
# Check if all characters are alphanumeric
print(password.isalnum()) # True
# Check if all characters are digits
print(password.isdigit()) # False

Trimming & Splitting

Python
text = " Python is fun! "
# Remove whitespace from start/end
print(text.strip()) # "Python is fun!"
# Split string into a list
words = "apple,banana,orange".split(",")
print(words) # ['apple', 'banana', 'orange']
# Join list elements into a string
print(" - ".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)

Python
1name = "Emma"
2age = 25
3gpa = 3.9
4
5# 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

Python
1# format() method
2info = "Name: {}, Age: {}, GPA: {:.1f}".format(name, age, gpa)
3print(info) # Output: Name: Emma, Age: 25, GPA: 3.9
4
5# Using numbered positions
6message = "{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)

Python
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":

P
y
t
h
o
n
0
1
2
3
4
5
-6
-5
-4
-3
-2
-1
Python
1text = "Python"
2
3# Accessing individual characters
4print(text[0]) # P (first character)
5print(text[1]) # y (second character)
6print(text[-1]) # n (last character)
7
8# 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:

Python
1import random
2
3def generate_username(name):
4 # Convert to lowercase
5 name = name.lower()
6
7 # Remove spaces
8 name = name.replace(" ", "")
9
10 # Take first 5 characters (or fewer if name is shorter)
11 short_name = name[:5]
12
13 # Generate random number between 100 and 999
14 random_num = random.randint(100, 999)
15
16 # Create username
17 username = short_name + str(random_num)
18
19 return username
20
21# Test with different names
22print(generate_username("John Smith")) # johns123
23print(generate_username("Maria Garcia")) # maria456
24print(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

MethodDescriptionExample
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 more

Understand how to work with collections of items in Python.

Learn more

Learn to interact with users and display information.

Learn more