In Python, a sequence of characters is called a string. Whether it’s a name, a sentence, or a single letter, understanding how to work with strings is essential. This guide will walk you through the most common operations like combining them, finding their length, and accessing individual characters.
🔗 Combining Strings: Concatenation
You can easily combine, or concatenate, two strings using the +
operator. This simply appends the second string to the end of the first one. For instance, if you have first_name = "John"
and last_name = "Doe"
, you can combine them like this: full_name = first_name + " " + last_name
. The result in full_name
would be “John Doe”.
📏 How Long is a String? The len() Function
To find out how many characters are in a string, you can use the built-in len()
function. It takes the string as its argument and returns its length as a non-negative integer. This is useful for all sorts of checks and loops. For example, len("Hello")
would return 5.
🎯 Accessing Individual Characters by Index
Every character in a string has a unique position, called an index. The first character is at index 0, the second at index 1, and so on. You can access a single character by placing its index in square brackets after the string variable. For example, if word = "Python"
, then word[0]
would give you “P”. This is incredibly powerful for tasks like getting a person’s initials from their full name.
These fundamental string operations are tools you’ll use constantly in your Python programming. Practice them by creating your own strings and manipulating them to see what’s possible!
—
Stephenson, Ben. The Python Workbook: A Brief Introduction with Exercises and Solutions. 3rd ed., Springer, 2025.
More Topics
- How to Pass Command Line Arguments to Your Python Script
- Solving the Classic FizzBuzz Problem in Python: A Step-by-Step Tutorial
- How to Solve the Pythagorean Theorem with a Python Script
- What’s the Difference Between Syntax, Runtime, and Logic Errors in Python?
- What Are Dictionaries in Python and How Do You Use Them?
- Thinking Recursively: A Beginner’s Introduction to Recursion in Python
- How to Read and Write Files in Python