Character strings, called strings, are one of the most commonly used data types in Python. Whether you want to display a message on screen with print, store a username, or manipulate text, you will constantly work with strings. If you want to master Python in depth, our comprehensive Python course will guide you step by step through learning this language, including advanced string manipulation.
Definition of a string in Python
A string (or str) is an ordered and immutable sequence of Unicode characters. In Python, a string is an object of type str that can contain letters, digits, symbols, spaces, and even special characters. Immutability means that once created, a string cannot be modified directly: any transformation operation returns a new string.
In Python 3, all strings are encoded in Unicode by default, which allows native handling of accented characters, emojis, and non-Latin alphabets.
You can create a string in several ways:
# With single quotes
name = 'Alice'
# With double quotes
message = "Hello world"
# With triple quotes (for multiline strings)
description = """This is
a string
on multiple lines"""
# With triple single quotes
other_description = '''This also works
on multiple
lines'''
Single and double quotes are functionally identical. The choice often depends on the content: if your text contains an apostrophe, use double quotes, and vice versa.
# Apostrophe in text: double quotes recommended
sentence = "It's exciting to learn Python"
# Quotes in text: single quotes recommended
citation = 'He said "hello" when entering'
Basic string operations
Concatenation and repetition
Python allows you to combine strings with the + operator (concatenation) and repeat them with the * operator:
# Concatenation
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # John Doe
# Repetition
separator = "-" * 30
print(separator) # ------------------------------
# Concatenation with +=
greeting = "Hello"
greeting += " everyone!"
print(greeting) # Hello everyone!
Accessing characters: indexing and slicing
Each character in a string has an index, starting at 0 for the first character. Python also supports negative indexing, where -1 refers to the last character:
word = "Python"
# Positive indexing
print(word[0]) # P
print(word[1]) # y
print(word[5]) # n
# Negative indexing
print(word[-1]) # n
print(word[-2]) # o
# Slicing (extracting substrings)
print(word[0:3]) # Pyt
print(word[2:]) # thon
print(word[:4]) # Pyth
print(word[::2]) # Pto (every other character)
print(word[::-1]) # nohtyP (reversed string)
Warning: attempting to access an index beyond the string's length will raise an IndexError. Use the len function to check a string's size before accessing it.
String length
The built-in len function returns the number of characters in a string:
text = "Hello Python"
print(len(text)) # 12
# Spaces count as characters
print(len(" ")) # 1
# An empty string has a length of 0
print(len("")) # 0
Essential string methods
Python provides a large number of built-in methods for manipulating strings. Here are the most common ones, grouped by category:
Case transformation
| Method | Description | Example | Result |
|---|---|---|---|
.upper() | Converts to uppercase | "python".upper() | "PYTHON" |
.lower() | Converts to lowercase | "PYTHON".lower() | "python" |
.capitalize() | First letter uppercase | "python".capitalize() | "Python" |
.title() | First letter of each word uppercase | "hello world".title() | "Hello World" |
.swapcase() | Swaps the case | "PyThOn".swapcase() | "pYtHoN" |
email = " User@Example.COM "
# Normalize an email
normalized_email = email.strip().lower()
print(normalized_email) # user@example.com
Searching and checking
sentence = "Python is a powerful programming language"
# Check for the presence of a word
print("Python" in sentence) # True
print("Java" in sentence) # False
# Find the position of a substring
print(sentence.find("powerful")) # 12
print(sentence.find("Java")) # -1 (not found)
# index() raises an exception if not found
# print(sentence.index("Java")) # ValueError
# Count occurrences
text = "abracadabra"
print(text.count("a")) # 5
# Start and end checks
filename = "report_2024.pdf"
print(filename.startswith("report")) # True
print(filename.endswith(".pdf")) # True
Testing methods
Python offers several methods to test the nature of characters contained in a string:
# Check content type
print("12345".isdigit()) # True
print("abc".isalpha()) # True
print("abc123".isalnum()) # True
print(" ".isspace()) # True
print("Hello".istitle()) # True
print("PYTHON".isupper()) # True
print("python".islower()) # True
Cleaning and replacing
# Remove unnecessary whitespace
text = " Hello Python "
print(text.strip()) # "Hello Python"
print(text.lstrip()) # "Hello Python "
print(text.rstrip()) # " Hello Python"
# Replace substrings
sentence = "I love Java, Java is great"
new_sentence = sentence.replace("Java", "Python")
print(new_sentence) # I love Python, Python is great
# Replace only the first occurrence
new_sentence = sentence.replace("Java", "Python", 1)
print(new_sentence) # I love Python, Java is great
Splitting and joining
The split() and join() methods are fundamental for converting between strings and list:
# Split a string into a list
sentence = "Python is fantastic"
words = sentence.split()
print(words) # ['Python', 'is', 'fantastic']
# Split with a custom separator
csv_line = "Alice,30,Paris,Developer"
values = csv_line.split(",")
print(values) # ['Alice', '30', 'Paris', 'Developer']
# Join a list into a string
words = ['Python', 'is', 'great']
result = " ".join(words)
print(result) # Python is great
# Join with another separator
path = "/".join(["home", "user", "documents"])
print(path) # home/user/documents
String formatting
Formatting allows you to dynamically insert values into a string. Python offers several approaches, but f-string are the recommended method since Python 3.6.
F-strings (recommended method)
name = "Alice"
age = 30
city = "Paris"
# Basic f-string
print(f"My name is {name} and I am {age} years old.")
# My name is Alice and I am 30 years old.
# Expressions inside f-strings
print(f"In 5 years, I will be {age + 5} years old.")
# In 5 years, I will be 35 years old.
# Method calls
print(f"My name in uppercase: {name.upper()}")
# My name in uppercase: ALICE
# Number formatting
price = 49.99
print(f"Price: {price:.2f} €") # Price: 49.99 €
print(f"Price: {price:>10.2f} €") # Price: 49.99 €
large_number = 1000000
print(f"Population: {large_number:,}") # Population: 1,000,000
The format() method
# Positional arguments
print("My name is {} and I am {} years old.".format("Alice", 30))
# Named arguments
print("My name is {name} and I live in {city}.".format(name="Alice", city="Paris"))
# Index arguments
print("{0} likes {1}, but {1} doesn't like {0}.".format("Alice", "Bob"))
The % operator (old method)
# Old method with the % operator
name = "Alice"
age = 30
print("My name is %s and I am %d years old." % (name, age))
f-string are not only more readable but also more performant than other formatting methods. Use them systematically in your modern Python projects.
Escape characters
Escape characters allow you to insert special characters into a string using the backslash \:
| Sequence | Description |
|---|---|
\n | New line |
\t | Tab |
\\ | Literal backslash |
\' | Single quote |
\" | Double quote |
\0 | Null character |
\u | Unicode character (e.g., \u00E9 for é) |
# Examples of escape characters
print("First line\nSecond line")
# First line
# Second line
print("Name\tFirst Name\tAge")
# Name First Name Age
print("He said \"hello\"")
# He said "hello"
# Raw strings: disable escape characters
path = r"C:\Users\name\documents"
print(path) # C:\Users\name\documents
Strings and iteration
Since a string is a sequence, you can iterate over it character by character, or use functions like enumerate to get both the index and the character simultaneously:
word = "Python"
# Iterate over each character
for character in word:
print(character, end=" ")
# P y t h o n
print() # New line
# With enumerate to get the index
for index, character in enumerate(word):
print(f"Index {index}: {character}")
# Index 0: P
# Index 1: y
# Index 2: t
# Index 3: h
# Index 4: o
# Index 5: n
You can also use list comprehensions to transform each character in a string:
word = "Python"
# Create a list of Unicode codes for each character
codes = [ord(c) for c in word]
print(codes) # [80, 121, 116, 104, 111, 110]
# Filter certain characters
vowels = [c for c in word if c.lower() in 'aeiouy']
print(vowels) # ['y', 'o']
Converting to and from strings
Python makes it easy to convert between strings and other data types:
# Convert to string
number = 42
floating = 3.14
my_list = [1, 2, 3]
print(str(number)) # "42"
print(str(floating)) # "3.14"
print(str(my_list)) # "[1, 2, 3]"
# Convert from a string
print(int("42")) # 42
print(float("3.14")) # 3.14
# Convert a string to a list of characters
characters = list("Python")
print(characters) # ['P', 'y', 't', 'h', 'o', 'n']
# Convert a string to a tuple
t = tuple("Python")
print(t) # ('P', 'y', 't', 'h', 'o', 'n')
Be careful when converting a string to a number. If the string does not contain a valid numeric value, Python will raise a ValueError exception. Use a try/except block to handle these cases.
Multiline strings and docstrings
Triple quotes allow you to create strings spanning multiple lines. They are also used for docstring, which document functions, classes, and modules:
def calculate_area(length, width):
"""Calculates the area of a rectangle.
Args:
length: The length of the rectangle.
width: The width of the rectangle.
Returns:
The area of the rectangle (length * width).
"""
return length * width
# Access the docstring
print(calculate_area.__doc__)
Best practices with strings in Python
1. Use f-strings for formatting: f-string are the most readable and performant method. Avoid the % operator in modern code.
2. Use join() to concatenate multiple strings: concatenation with + in a loop creates many intermediate objects. Use "".join() instead:
# ❌ Inefficient
result = ""
for word in ["Python", "is", "great"]:
result += word + " "
# ✅ Efficient
result = " ".join(["Python", "is", "great"])
3. Use in to check for substring presence: this is more readable than using find() for a simple presence test.
# ❌ Less readable
if sentence.find("Python") != -1:
print("Found")
# ✅ More readable
if "Python" in sentence:
print("Found")
4. Normalize strings for comparisons: use .lower() or .casefold() for case-insensitive comparisons:
user_input = "Python"
if user_input.lower() == "python":
print("Match found!")
# casefold() is more aggressive for international characters
print("straße".casefold()) # strasse
5. Remember that strings are immutable: every modification creates a new string. If you need to make many modifications, consider using a list of characters and then joining it.
Frequently asked questions
What is the difference between single and double quotes in Python?
There is no functional difference between single quotes ('...') and double quotes ("...") in Python. Both create an identical str object. The choice is a matter of style and convenience: use double quotes if your text contains apostrophes, and vice versa. The PEP 8 convention does not impose a preference, but consistency within a project is recommended.
Are strings immutable in Python?
Yes, strings are immutable in Python. This means you cannot modify a character at a given index (for example, my_string[0] = "A" will raise a TypeError). Any operation that seems to modify a string (such as replace(), upper(), or concatenation) actually creates a new string. This immutability allows strings to be used as keys in dict and as elements in set.
How do you convert a string to a number in Python?
Use int() to convert to an integer and float() to convert to a floating-point number. For example: int("42") returns 42 and float("3.14") returns 3.14. If the string is not a valid number, Python will raise a ValueError exception. You can use the .isdigit() method to check beforehand whether a string contains only digits, or use a try/except block to handle conversion errors robustly.
How can you learn to manipulate strings and Python in general?
String manipulation is a fundamental skill in Python. To gain complete mastery of the language, from basics to advanced concepts like regular expressions and text data processing, we recommend following our dedicated Python course on Believemy. You will find practical exercises, real-world projects, and structured guidance to progress effectively.