Python | Split String and Get First N Characters

Rate this post

Summary: To get the first “N” characters of a string slice, the string from the starting index until the Nth character using Python’s slice notation.

Minimal Example

text = "akjvdkavkjsdvkja"
# Get first 3 characters

# OUTPUT: akj

Problem Formulation

📜Problem: Given a string. How will you get the first “N” characters of the string?

Example 1

In the following example, you just have to extract the first 5 characters from the given string.

text = 'abcdefghijklmnopqr'
n = 5


Example 2

In the following example, you first have to split the string and get the words/substrings out of it and then extract the first three characters from each substring.

# Input
text = "eagdef-ernopqr-essvwxyz"
# Output

Solution: Split and Slice the String

Approach to Solve Example 1: Slice the string using square bracket notation and extract the required number of characters using their indices.

Since we need the first 5 characters, you can simply slice the string starting from 0 until 5. This means the start value is 0 while the stop value is 5.


text = 'abcdefghijklmnopqr'
n = 5

# abcde

Approach to Solve Example 2: You have to go a step further to solve the second scenario. Here, you have to first split the string using the given delimiter (“-“) which will create a list of substrings. Now in order to extract the first three characters from each substring simply iterate through each item of the list using a for loop and slice out the first three characters from each element in each iteration with the help of slice notation.

text = "eagdef-ernopqr-essvwxyz"
res = text.split('-')
for i in res:
    print(i[:3], end='')

# eagerness

Graphical Illustration:


Slicing is a concept to carve out a substring from a given string. Use slicing notation s[start:stop:step] to access every step-th element starting from index start (included) and ending in index stop (excluded). All three arguments are optional, so you can skip them to use the default values (start=0stop=len(lst)step=1). For example, the expression s[2:4] from string 'hello' carves out the slice 'll' and the expression s[:3:2] carves out the slice 'hl'.

Related Video:

The Ultimate Guide to Slicing in Python

Related Read: Introduction to Slicing in Python

Bonus Questions

🍎Qs 1: How to Split a String After Every N Characters?

Solution: One of the easiest ways to split a string after every n character is to use a list comprehension to and slice the string accordingly to extract every n character of the given string and store them in a list. The items of this list represent the required split substrings.


given_string = 'abcdef'
n = 3
print([(given_string[i:i+n]) for i in range(0, len(given_string), n)])
# OUTPUT: ['abc', 'def']

Read More: Python | Split String Every “N” Characters

🍎Qs 2: How to Split a String and Get the Nth Element?

Solution: Split the string normally at the occurrence of the given delimiter using the split method. To extract the required element from the list use its index within square brackets.


text = "Welcome to the world of Python!"
res = text.split()
print("Split substrings: ", res)
print("Required Element: ", res[3])

# Split substrings:  ['Welcome', 'to', 'the', 'world', 'of', 'Python!']
# Required Element:  world

Read More: Python | Split String Get Element

🍎Qs 3: How to Split a String and Get First N elements?

Approach: Split the string using the split function and the given delimiter. Then extract the first “N” characters from the split list of substrings using their index.


text = 'abc-efg-xyz-lmn-pqr'
res = text.split('-')
for i in range(3):
    print(res[i], end=" ")

# abc efg xyz 

🍎Qs 4: How to Split a String and Get the Last “N” Elements?

Solution: Split the string using Python’s built-in split method and the given separator. To extract the last three elements from this split list, iterate in a reverse range starting from -3 until 0. This will allow you to grab the last three elements from the list using their negative indices.


text = 'abc-efg-xyz-lmn-pqr'
res = text.split('-')
for i in range(-3, 0):
    print(res[i], end=" ")

# xyz lmn pqr 


I hope the questions and their solutions discussed in this article have helped you. Please subscribe and stay tuned for more interesting solutions and discussions in the future.

Happy coding! 🙂

Check out my new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Publisher Link: