Get the First or Last N Characters of a Python String
Get the first or last N characters of a Python string with text[:n] and text[-n:], including zero, oversized and combined slices.
Use text[:n] to get the first n characters of a Python string and text[-n:] to get the last n characters:
text = "Uncopyrightable"
print(text[:5]) # Uncop
print(text[-5:]) # table
Python slicing does not raise an error when n is longer than the string. It returns all available characters.
Get the first N characters
The slice text[:n] starts at the beginning and stops before index n:
text = "Python"
print(text[:1]) # P
print(text[:3]) # Pyt
print(text[:10]) # Python
The stop position is exclusive. text[:3] therefore returns the characters at indexes 0, 1 and 2.
Get the last N characters
Use a negative starting index and leave the stop position empty:
text = "Python"
print(text[-1:]) # n
print(text[-3:]) # hon
print(text[-10:]) # Python
The colon matters. text[-3] returns one character, while text[-3:] returns the final three characters.
What happens when N is zero?
The first-zero slice is empty:
text = "Python"
print(text[:0]) # ''
Be careful with the last-zero form:
print(text[-0:]) # Python
Python treats -0 as 0, so text[-0:] means text[0:] and returns the whole string. Handle zero explicitly when n may be zero:
last_n = text[-n:] if n else ""
Get both the first and last N characters
Concatenate the two slices:
text = "Uncopyrightable"
n = 3
result = text[:n] + text[-n:]
print(result) # Uncble
If the slices overlap because n is more than half the string length, characters will appear twice. Cap n or decide how overlapping input should behave for your application.
Slice syntax
A slice has the form:
text[start:stop:step]
startis included.stopis excluded.stepcontrols how many positions to move each time.- Omitting
startbegins at the start of the string. - Omitting
stopcontinues to the end.
For one character rather than several, see how to get the first character or last character of a Python string.