Get the first N characters of a String in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
4 min

banner

# Table of Contents

  1. Get the first N characters of a String in Python
  2. Getting the first N characters and the remainder
  3. Get the first N characters of a String using a for loop

# Get the first N characters of a String in Python

Use string slicing to get the first N characters of a string, e.g. first_n = string[:n].

The slicing operation will return a new string that starts at index 0 and contains the first N characters of the original string.

main.py
string = 'bobbyhadz.com' first_char = string[0] print(first_char) # ๐Ÿ‘‰๏ธ b # โœ… get the first 2 characters of a string first_2 = string[:2] print(first_2) # ๐Ÿ‘‰๏ธ bo # โœ… get the first 3 characters of a string first_3 = string[:3] print(first_3) # ๐Ÿ‘‰๏ธ bob # โœ… get the first 5 characters of a string first_5 = string[:5] print(first_5) # ๐Ÿ‘‰๏ธ bobby

get first n characters of string

The code for this article is available on GitHub

We used string slicing to get the first N characters of a string.

The syntax for string slicing is my_str[start:stop:step].

The start index is inclusive, whereas the stop index is exclusive (up to, but not including).

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(my_str) - 1.

The slice string[:2] starts at index 0 and goes up to, but not including index 2.

main.py
string = 'bobbyhadz.com' first_2 = string[:2] print(first_2) # ๐Ÿ‘‰๏ธ bo

In other words, the slice returns the characters at index 0 and 1.

# Explicitly specifying the start index is not necessary

You could also explicitly specify a start index of 0, but if you don't, a value of 0 is implied.

main.py
string = 'bobbyhadz.com' first_2 = string[0:2] print(first_2) # ๐Ÿ‘‰๏ธ bo first_2 = string[:2] print(first_2) # ๐Ÿ‘‰๏ธ bo

not explicitly specifying start index

The code for this article is available on GitHub

The two examples in the code sample achieve the same result.

# If n is greater than the string's length, the entire string is returned

If the specified value of n is greater than the string's length, the entire string is returned.

main.py
string = 'bobbyhadz.com' print(string[:100]) # ๐Ÿ‘‰๏ธ bobbyhadz.com

The string doesn't contain 100 characters, so a slice that represents the entire string is returned.

# If the string is empty, an empty string is returned

The string slicing operation won't cause an error if used with an empty string.

main.py
string = '' print(repr(string[:100])) # ๐Ÿ‘‰๏ธ ''

The string in the example is empty, so trying to get its first N characters returns an empty string.

# Getting the first N characters and the remainder

If you need to get the remainder of the string, use a start index of n.

main.py
string = 'bobbyhadz.com' n = 5 # โœ… Get the first 5 characters of a string first_5 = string[:n] print(first_5) # ๐Ÿ‘‰๏ธ bobby # โœ… Get the characters after the first 5 after = string[n:] print(after) # ๐Ÿ‘‰๏ธ hadz.com

getting first n characters and remainder

The code for this article is available on GitHub

The slice string[:5] starts at index 0 and goes up to, but not including index 5.

The slice string[5:] starts at index 5 and goes to the end of the string.

It is very important to note that start indexes are inclusive, whereas stop indexes are exclusive (up to, but not including).

If you need to get the last N characters of a string, use a negative start index.

main.py
string = 'bobbyhadz.com' last_2 = string[-2:] print(last_2) # ๐Ÿ‘‰๏ธ 'om'

Negative indices can be used to count backward, e.g. string[-1] returns the last character in the string and string[-2] returns the second to last character.

The slice string[-2:] starts at the second to last character in the string and goes to the end.

You can also use a for loop to get the first N characters of a string.

# Get the first N characters of a String using a for loop

This is a three-step process:

  1. Declare a new variable that stores an empty string.
  2. Use a for loop to iterate over the string.
  3. Append the first N characters of the original string to the new string.
main.py
string = 'bobbyhadz.com' first_n = '' n = 5 for char in string: if n < 1: break n -= 1 first_n += char print(first_n) # ๐Ÿ‘‰๏ธ 'bobby'

getting first n characters using for loop

The code for this article is available on GitHub

We used a for loop to iterate over the string.

On each iteration, we check if the value stored in the n variable is less than 1.

If the condition is met, we exit the for loop.

The break statement breaks out of the innermost enclosing for or while loop.

Otherwise, we use the addition (+) operator to add the current character to the new string.

The += operator is a shorthand for first_n = first_n + char.

Similarly, the -= operator is a shorthand for n = n - 1.

Note that this approach is much less efficient than using string-slicing directly.

# Creating a reusable function

You can also create a reusable function that returns the first N characters of a string.

main.py
def get_first_n(string, n): return string[:n] string = 'bobbyhadz.com' print(get_first_n(string, 2)) # ๐Ÿ‘‰๏ธ bo print(get_first_n(string, 3)) # ๐Ÿ‘‰๏ธ bob print(get_first_n(string, 5)) # ๐Ÿ‘‰๏ธ bobby

creating a reusable function

The code for this article is available on GitHub

The function takes a string and n as parameters and returns the first n characters of the supplied string.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev