How do I get a substring of a string in Python?
Share
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
You must login to ask question.
Here is the syntax:
Where,
start
: The starting index of the substring. The character at this index is included in the substring. Ifstart
is not included, it is assumed to equal to 0.end
: The terminating index of the substring. The character at this index is not included in the substring. Ifend
is not included, or if the specified value exceeds the string length, it is assumed to be equal to the length of the string by default.step
: Every “step” character after the current character to be included. The default value is 1. Ifstep
is not included, it is assumed to be equal to 1Basic Usage
string[start:end]
: Get all characters fromstart
toend
– 1string[:end]
: Get all characters from the beginning of the string toend
– 1string[start:]
: Get all characters fromstart
to the end of the stringstring[start:end:step]
: Get all characters fromstart
toend
– 1, not including everystep
characterExamples
1. Get the first 5 characters of a string
Output:
Note:
print(string[:5])
returns the same result asprint(string[0:5])
2. Get a substring 4 characters long, starting from the 3rd character of the stringOutput:
3. Get the last character of the string
Output:
Notice that the
start
orend
index can be a negative number. A negative index means that you start counting from the end of the string instead of the beginning (from the right to left). Index -1 represents the last character of the string, -2 represents the second to last character and so on. 4. Get the last 5 characters of a stringOutput:
5. Get a substring which contains all characters except the last 4 characters and the 1st character
Output:
6. Get every other character from a string
Output: