Get First N Characters of String in Python

Here, we will develop a Python program to get the first n characters of a string. If the string was “Knowprogram” then print first n characters like “K”, “Kn”, “Know”, etc. We will discuss how to get the first n characters from the given string using [] operator, and slice operator.

Python Program to Get First N Characters of String

We will take a string and take the value of n while declaring the variables. Then, we will run the loop from 0 to n and append the string into the empty string (first_char). 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. As indexing of characters in a string starts from 0 to n. Finally, the first n characters will be displayed on the screen.

# Python Program get first n characters of string

# take string
string = input('Enter any string: ')

# take value of n
n = int(input('Enter n: '))

# get first n characters
first_char = ""
for i in range(0, n):
    first_char = first_char + string[i]

# printing first n characters of string
print('First', n, 'character:', first_char)

Output for the different input values:-

Enter any string: Python
Enter n: 3
First 3 character: Pyt

Enter any string: Know Program
Enter n: 7
First 7 character: Know Pr

Enter any string: Know Program
Enter n: 25
Traceback (most recent call last):
File “main.py”, line 12, in
first_char = first_char + string[i]
IndexError: string index out of range

While using the [] operator, we need to be careful about the out-of-range error. If we try to access the index position in a string that does not exist, like a position that is larger than the size of the string, then it will give IndexError.

Get First N Characters of String in Python

We will get the first n characters of the given string using the slice operator. The [:n] specifies the character at index n. The string[:n] specifies the first n characters of the given string.

# Python Program get first n characters of string

# take string
string = input('Enter any string: ')

# take value of n
n = int(input('Enter n: '))

# get first n characters
first_char = string[:n]

# printing first n characters of string
print('First', n, 'character:', first_char)

Output for the different input values:-

Enter any string: Slicing
Enter n: 4
First 4 character: Slic

Enter any string: First n character
Enter n: 12
First 12 character: First n char

Also See:- Extract Numbers From String Python

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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