Languages
[Edit]
EN

Python - get first 3 characters of string

0 points
Created by:
Keisha-Acosta
260

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 is 0),
  • 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 is 1)

 

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

Python - string (popular problems)

Python - get first 3 characters of string
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join