EN
Python - get first 3 characters of string
0
points
In this article, we would like to show you how to get the first 3 characters of a string in Python.
Quick solution:
string[start_index: end_index]
or
string[start_index: end_index: step]
Where:
start_index- index position, from where it will start fetching the characters (default value is0),end_index- index position, where it will end fetching the characters (default value is end of the string),step- interval between each character (default value is1)
Practical examples
1. Get first 3 characters of a string
In this example, we get the first 3 characters of the "dirask" string by index (0 to 3).
string = "dirask"
first_characters = string[0: 3]
print("First 3 characters:", first_characters)
Output:
First 3 characters: dir
2. Get every second character (with step)
In this example, we get every second character from the first 5 characters (0 - 5) of the "dirask" string.
string = "dirask"
characters = string[0: 5: 2]
print(characters)
Output:
drs