Extract the First N Characters from a String in Python

As a developer, I was working on a project where I had to clean up customer data in a large dataset. One of the tasks was to extract the first few characters from a string, such as trimming ZIP codes to the first three digits or keeping only the first five characters of a product code.

At first, I thought this would require a complicated function. But as I explored different approaches, I realized Python makes this task surprisingly simple. I’ve used multiple methods to get the first N characters of a string, and each one is useful depending on the situation.

In this tutorial, I’ll show you several easy ways to extract the first N characters from a string in Python. I’ll also share some practical examples that I’ve personally used in real-world projects.

Method 1: Use Python String Slicing

We will use string slicing in Python, which allows us to extract substrings by specifying a start and end index. To get the first n characters of a string, we can slice the string from index 0 to N.

Code:

text = "The Statue of Liberty stands tall in New York Harbor."
n = int(input("Enter range : "))
first_n_characters = text[:n] 
print(f"First {n} characters:", first_n_characters)

Output

Enter range : 13 
First 13 characters: The Statue of

You can refer to the screenshot below to see the output.

How to Get the First N Characters of a String in Python

In this code, text[:13] extracts the substring from index 0 to 12 (10 characters) from the text string.

Method 2: Use Negative Indexing

We are using negative indexing in slicing to extract the first n characters of a string by counting characters from the end of the string.

Here’s a simple example to get the first n characters of a string in Python.

Code:

city = "Los Angeles"
n = int(input("Enter range : "))
first_n_chars = city[-len(city) : -len(city)+(n)]
print(f"First {n} characters:", first_n_chars)

Output

Enter range : 3
First 3 characters: Los

You can refer to the screenshot below to see the output.

Get the first N characters of a String in Python

We are taking -len(city) to target the first character of the string and giving the endpoint as len(city)+(n) to extract the letters in the string according to user input.

Method 3: Use a For Loop in Python

Using the for loop, we can iterate over the string and concatenate characters until we reach the desired length of N. The for loop offers flexibility for dynamic conditions and is suitable for scenarios with more complex extraction logic.

Code:

state = "California"
n = int(input("Enter the range : "))
first_n_characters = ''

for char in state:
    if len(first_n_characters) < n:
        first_n_characters += char
    else:
        break
print(f"First {n} characters:", first_n_characters)

Output

Enter the range : 5
First 5 characters: Calif

You can refer to the screenshot below to see the output.

How to display the first few characters of a string in Python

This code iterates over each character of the state string, appending them to first_five_chars until its length reaches 5.

Method 4: Use a While Loop

We can also use a while loop to iterate over every character to extract the first N characters of a string until the desired length is achieved. It provides flexibility for handling strings of varying lengths.

Code:

text = "The Empire State Building is an iconic landmark in New York City."
first_n_chars = ''
index = 0
N = int(input("Enter the range : "))

while len(first_n_chars) < N and index < len(text):
    first_n_chars += text[index]
    index += 1
print("First", N, "characters:", first_n_chars)

In this example, A while loop is initialized to iterate until the length of first_n_chars reaches N or the end of the string text is reached.

while len(first_n_chars) < N and index < len(text):
    first_n_chars += text[index]
    index += 1

Output

Enter the range : 10
First 10 characters: The Empire

You can refer to the screenshot below to see the output.

Get first N characters in python

Within each iteration, the character at the current text index is appended to first_n_chars, and the index is incremented.

Method 5: Use Python’s Regular Expression

The re.match() is a built-in function of the re module in Python that searches for the specified pattern at the beginning of the string text. The group() method retrieves the matched substring if a match is found.

Code:

import re

n = int(input("Enter range: "))
text = "The Grand Canyon is a natural wonder."
first_n_chars = rematch(r'.{%d}' % n, text).group()
print(f"First {n} characters:", first_n_chars)

Output

Enter range: 9
First 9 characters: The Grand

You can refer to the screenshot below to see the output.

get first n letters in python

I’ve used a regular expression pattern r’.{%d}’ % n, where the user-input value of n replaces %d, and the code matches the first n characters of the string text in Python.

Method 6: Use Python’s join() Method

We can use str.join() to join the elements of iterables in Python, and we can use it with a list comprehension to get the first n characters of a Python string.

Code:

text = "The Golden Gate Bridge spans the Golden Gate Strait."
n = int(input("Enter the range : "))
first_n_chars = ''.join(text[i] for i in range(n))
print(f"First {n} characters:", first_n_chars)

Output

Enter the range : 7
First 7 characters: The Gol

You can refer to the screenshot below to see the output.

extract first n letters in python

I used the join() method with list comprehension to create a list of extracted characters according to the user input range, and concatenated all the characters into a single string by using the join() method in Python.

Conclusion

This article explains how to get the first N characters of a string in Python through multiple methods, each offering its unique advantages. We explored six methods or techniques: string slicing, negative indexing, loops (both for and while), regular expressions, and the join() method.

Understanding and utilizing these methods helps you efficiently manipulate text data in various applications.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.