Python: How to get first N characters in a string?

In this article, we will discuss how to fetch/access the first N characters of a string in python. This N can be 1 or 3 etc.

Python string is a sequence of characters and each character in it has an index number associated with it. For example, we have a string variable sample_str that contains a string i.e.

sample_str = "Hello World !!"

Each character in this string has a sequence number, and it starts with 0 i.e.

  • ‘H’ has index 0
  • ‘e’ has index 1
  • ‘l’ has index 2
  • ‘l’ has index 3
  • ‘o’ has index 4
  • ‘ ‘ has index 5
  • ‘W’ has index 6
  • ‘o’ has index 7
  • ‘r’ has index 8
  • ‘l’ has index 9
  • ‘d’ has index 10
  • ‘!’ has index 11
  • ‘!’ has index 12

In python String provides an [] operator to access any character in the string by index position. We need to pass the index position in the square brackets, and it will return the character at that index. This index position can be a positive or negative int value.

Like, sample_str[i] will return a character at index i-th index position. Let’s use it.

Get the first character of a string in python

As indexing of characters in a string starts from 0, So to get the first character of a string pass the index position 0 in the [] operator i.e.

sample_str = "Hello World !!"

# Get first character of string i.e. char at index position 0
first_char = sample_str[0]

print('First character : ', first_char)

Output:

First character :  H

It returned a copy of the first character in the string. You can use it to check its content or print it etc.

In the above example, we fetched the first character or the string, but what if we want more like, get the first three characters of a string or first four, etc. Basically we want to access a substring of given length from the start of the string. How to do that?

Get first N characters in a string

In python, apart from index position, subscript operator, i.e. [] can accept a range too i.e.

string[ start_index_pos: end_index_pos: step_size]

It returns a slice the string, i.e. a substring. If we want to get more than one character out of a string i.e. fetch a substring, then we can pass these range elements in [] operator,

  • start_index_pos: Index position, from where it will start fetching the characters, the default value is 0
  • end_index_pos: Index position till which it will fetch the characters from string, default value is the end of string
  • step_size: Interval between each character, default value is 1.

To get the first N characters of the string, we need to pass start_index_pos as 0 and end_index_pos  as N i.e.

sample_str[ 0 : N ]

The value of step_size will be default i.e. 0. It will slice the string from 0th index to n-1-th index and returns a substring with first N characters of the given string.

Let’s use this,

Get first three characters of a string in python

sample_str = "Hello World !!"

# Get First 3 character of a string in python
first_chars = sample_str[0:3]

print('First 3 character : ', first_chars)

Output:

First 3 character :  Hel

We sliced the string from 0 the index position to (3 -1) index position and we got a substring containing the first three characters of the string.

Get first four characters of a string in python

sample_str = "Hello World !!"

# Get First 4 character of a string in python
first_chars = sample_str[0:4]

print('First 4 character : ', first_chars)

Output:

First 4 character :  Hell

We sliced the string from 0 the index position to (4 -1) index position, and we got a substring containing the first four characters of the string.

IndexError: string index out of range

While using [] operator, we need to be careful about out of range error i.e. if we try to access the index position in a string that doesn’t exist, like a position that is larger than the size of the string, then it will give IndexError like this,

sample_str = "Hello World !!"

# Accessing out of range element causes error
first_char = sample_str[20]

It will give the error,

IndexError: string index out of range

Because we accessed index position 20 that doesn’t exist, it is larger than the size of the string. Therefore, we should always check for the size of string before accessing the character based on the index position. Like this,

sample_str = "Hello World !!"

if len(sample_str) > 20:
    # Accessing out of range element causes error
    first_char = sample_str[20]
else:
    print('Sorry out of range position')

Output:

Sorry out of range position

The complete example is as follows,

sample_str = "Hello World !!"

print('**** Get first character of a String in python ****')

# Get first character of string i.e. char at index position 0
first_char = sample_str[0]

print('First character : ', first_char)

print('**** Get first N characters of a String in python ****')

print('** Get first 3 characters of a String in python **')

# Get First 3 character of a string in python
first_chars = sample_str[0:3]

print('First 3 character : ', first_chars)

print('** Get first 4 characters of a String in python **')

# Get First 4 character of a string in python
first_chars = sample_str[0:4]

print('First 4 character : ', first_chars)

print('*** Handle IndexError ***')

sample_str = "Hello World !!"

if len(sample_str) > 20:
    # Accessing out of range element causes error
    first_char = sample_str[20]
else:
    print('Sorry out of range position')


Output:

**** Get first character of a String in python ****
First character :  H
**** Get first N characters of a String in python ****
** Get first 3 characters of a String in python **
First 3 character :  Hel
** Get first 4 characters of a String in python **
First 4 character :  Hell
*** Handle IndexError ***
Sorry out of range position

Summary

We learned about different ways to fetch first N characters from a string in Python.

1 thought on “Python: How to get first N characters in a string?”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top