Python String - Get first N characters


Python String - Get first N characters

To get the first N characters from a string in Python, you can slice the string from index=0 to index=N, i.e., for the string slice start would be 0, and stop would be N.

In this tutorial, you will learn how to get the first N characters from a string in Python using string slicing, with examples.

1. Get first N characters from string using string slicing in Python

If x is the given string, then use the following expression to get the substring with the first n characters from the original string.

x[0:n]

Since, 0 is the default value for start parameter, you can avoid specifying it, as shown below.

x[:n]

In the following program, we take a string value in variable x, get the first 4 characters, and print it to output.

Python Program

# Input string
x = "Hello, World!"

# Number of characters to retrieve
n = 4

# Get the first n characters
first_n_characters = x[:n]

# Print the result
print(first_n_characters)

Output

Hell

Related Tutorials

Summary

In this tutorial, we learned how to get the first N character from a string using string slicing, with the help of examples.