How to Get the First N Characters of a String in Python
Extracting a substring from the beginning of a string is a common operation.
This guide explains how to get the first N characters of a string in Python, primarily using string slicing, the most efficient and Pythonic method. We'll also briefly cover a less efficient for
loop approach for comparison.
Getting the First N Characters with String Slicing (Recommended)
String slicing is the most direct, efficient, and Pythonic way to get the first N characters. The syntax is string[:n]
.
string = 'tutorialreference.com'
first_2 = string[:2] # Get the first 2 characters
print(first_2) # Output: tu
first_3 = string[:3] # Get the first 3 characters
print(first_3) # Output: tut
first_5 = string[:8] # Get the first 8 characters
print(first_5) # Output: tutorial
string[:n]
creates a new string consisting of characters from the beginning ofstring
up to (but not including) indexn
.- String slicing is generally very fast in Python, so it's the best for most use cases.
Handling Edge Cases
-
n
is larger than the string length: Ifn
is greater than the string's length, slicing simply returns the entire string. No error occurs.string = 'tutorialreference.com'
print(string[:100]) # Output: tutorialreference.com -
Empty string: Slicing an empty string always returns an empty string, regardless of
n
.string = ''
print(repr(string[:100])) # Output: ''
Getting the Remainder
To get the remainder of the string after first n characters, use slicing again, this time with a start index:
string = 'tutorialreference.com'
n = 8
first_8 = string[:n] # first 8 characters
print(first_8)
after = string[n:] # remainder
print(after)
Output:
tutorial
reference.com
- The slice
string[:8]
will return a new string that starts at index 0 and goes up to, but not including, index 8. - The slice
string[n:]
will start at index 8 and go until the end of the string.
Getting the First N Characters with a for
Loop (Less Efficient)
While slicing is preferred, you can use a for
loop. This is much less efficient and less readable, so it's generally not recommended unless you have a very specific reason to do so:
string = 'tutorialreference.com'
first_n = ''
n = 8
for char in string:
if n < 1:
break # Stop when we've collected n characters
n -= 1
first_n += char
print(first_n) # Output: tutorial
- This will loop until the variable
n
becomes less than 1. - This approach is significantly less efficient than slicing, and harder to read. Avoid it unless you have a compelling reason.
Creating a reusable function
You can also create a function that accepts a string and a number n, and returns the slice containing first n characters:
def get_first_n(string, n):
return string[:n]
string = 'tutorialreference.com'
print(get_first_n(string, 2)) # Output: tu
print(get_first_n(string, 3)) # Output: tut
print(get_first_n(string, 8)) # Output: tutorial
- This approach is useful if you have to perform this operation multiple times in your code.