Sign Up

Sign In

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Please make a payment to be able to ask a question.

Pay to ask a question

Please make a payment to be able to add post.

Pay to add a post

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

The Complete Guide to Substringing a String in Python

There are many ways to substring a string in Python. This is often referred to as “slicing”.

Here is the syntax:

string[start:end:step]

Where,

start: Substring starting index. The character at this index is included in the substring. If start is not included, start is assumed to be 0.

end: The ending index of the substring. If end is omitted, or if the specified value exceeds the string length, it is assumed to be equal to the length of the string.

step: The default value of step is 1. If step is not included, it is assumed to be equal to 1.

Python Interactive Scrim for Substringing a String

string = “freeCodeCamp”
# Syntax: string[start:end:step]

Basic Usage

string[start:end]: From start to end, get all characters minus one

string[:end]: From the beginning to the end of the string, get all the characters

string[start:]: From start to end, get all characters

string[start:end:step]: Count all characters from start to end minus one, not including every step character

Examples

1. Get the first five characters of a string

string = "freeCodeCamp"
print(string[0:5])

Output

> freeC

Note: There is no difference between print(string[:5]) and print(string[0:5]).

2. Starting from the 3rd character in the string, get a substring of 4 characters

string = "freeCodeCamp"
print(string[2:6])

Output

> eeCo

3. Find the string’s last character

string = "freeCodeCamp"
print(string[-1])

Output

> p

Note: The start or end index can be negative. A negative index means counting from the end of the string rather than the beginning (from right to left).

The last character in the string is represented by index -1, the second to last character by index -2, and so on.

4. Find the last five characters in a string

string = "freeCodeCamp"
print(string[-5:])

Output

> eCamp

5. Get a substring that contains all characters except the last four and the first

string = "freeCodeCamp"
print(string[1:-4])

Output

> reeCode

6. From a string, get every other character

string = "freeCodeCamp"
print(string[::2])

Output

> feCdCm

Related Posts

Leave a comment