How do I get a substring of a string in Python?
Stack How?
Stackorigin – The Community of Question and Answers Latest Articles
Read More About Python List Comprehension with examples
Python List Comprehension: Python List comprehension provides a much more short syntax for creating a new list based on the values of an existing list. Advantages of List Comprehension in Python: Time Efficient than loop Space Efficient than loop Needs ...
Do not accept an offer letter from companies.
Do not accept an offer letter from companies without verifying the following points. Designation Salary Details & CTC Distribution Leave Policies Working Hours & Days Medical Coverage/Insurance Probation Period Notice Period Benefits and Perks Bonus F&F Policy
How to call API using Ajax
AJAX stands for Asynchronous JavaScript and XML and its used for to make calls to the server to fetch some data. In this article, we will learn how to implement a simple API call using AJAX technology. How to use GET ...
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: