- How to Get a Substring From a String in Python
- Python substring
- How Indexing Works
- Python substring examples
- End index only
- Start index only
- No Indexes specified
- How to get the first part from a string
- Get last part from a string
- Get first character from a string
- Get last character from a string
- Substring from right side of the string
- How to get the last 9 character from Python string
- Get a substring which contains all characters except the last 10 characters
- Step in Python substring
- Add step 1
- Get every other character from a python string
- Change step to 2
- Change step to 3
- Reverse a string in Python
- Python Substring – How to Slice a String
- How to Generate a Substring in Python
- How to Get the First n Characters of a String in Python
- How to Get the Middle Characters of a String via Python Substrings
- How to Get the Last Character of a String in Python
- How to Get the Last n Characters of a String in Python
- How to Slice the String with Steps via Python Substrings
- How to Check if a Substring is Present Within a String in Python
- Another Way to Check if the Python Substring is Present in the String
- How to Get the Character of a Given Index in a String in Python
- How to Create a List of Substrings from a String in Python
- How to Reverse a String in Python with Negative Steps
- How to Count How Many Times a Substring is Present in a String in Python
- Final Thoughts on Python Substrings
- How to Substring a String in Python
- Here’s an Interactive Scrim of How to Substring a String in Python
- Basic Usage
- Examples
How to Get a Substring From a String in Python
In Python, Strings are arrays of bytes representing Unicode characters. It’s possible to access individual characters of a string by using array-like indexing . Like an array data type that has items that correspond to an index number , each of a string’s characters also correspond to an index number, starting with the index number 0.
Python substring
Python has no substring methods like substring() or substr(). Instead, we use slice syntax to get parts of existing strings. Python slicing is a computationally fast way to methodically access parts of your data. The colons (:) in subscript notation make slice notation — which has the arguments, start, stop and step . It follows this template:
- start — Starting index of string, Default is 0.
- end — End index of string which is not inclusive .
- step — An integer number specifying the step of the slicing. Default is 1.
How Indexing Works
You can make any of these positive or negative numbers for indexing. The meaning of the positive numbers is straightforward (from start), but for negative numbers, just like indexes in Python, you count backwards from the end for the start and stop, and for the step (optional), you simply decrement your index.
Python substring examples
End index only
Start index only
No Indexes specified
How to get the first part from a string
Get last part from a string
Get first character from a string
Get last character from a string
Substring from right side of the string
You may also get the substring from the right side of the string. A negative index means that you start counting from the end of the string(from right to left) instead of the beginning. Index [-1] represents the last character of the string, [-2] represents the second to last character.
How to get the last 9 character from Python string
Get a substring which contains all characters except the last 10 characters
Step in Python substring
The third parameter specifies the step , which refers to how many characters to move forward after the first character is retrieved from the string. Python defaults to the step of 1, so that every character between two index numbers is retrieved.
Add step 1
Here, we get the same results by including a third parameter with a step of 1.
Get every other character from a python string
Change step to 2
Here you can see, you get the every other character from python string .
Change step to 3
Reverse a string in Python
- Python Datatype conversion
- Python Mathematical Function
- Basic String Operations in Python
- How to check if Python string contains another string
- Check if multiple strings exist in another string : Python
- Memory Management in Python
- Python Identity Operators
- What is a None value in Python?
- How to Install a Package in Python using PIP
- How to update/upgrade a package using pip?
- How to Uninstall a Package in Python using PIP
- How to call a system command from Python
- How to use f-string in Python
- Python Decorators (With Simple Examples)
- Python Timestamp Examples
Python Substring – How to Slice a String
Davis David
In Python, a string is a sequence of characters that may contain special characters or alphanumeric characters.
An example of a string is «we meet on Friday at 08:00 am«. And you can access specific sub-parts of the string commonly known as substrings.
We can define a substring as a sequence of characters within a string. From the previous example, Python substrings can be «Friday», «at», and «meet», for example.
How to Generate a Substring in Python
Python provides different ways and methods to generate a substring, to check if a substring is present, to get the index of a substring, and more.
You can extract a substring from a string by slicing with indices that get your substring as follows:
- start — The starting index of the substring.
- stop — The final index of a substring.
- step — A number specifying the step of the slicing. The default value is 1.
Indices can be positive or negative numbers. The positive indices start from the beginning and go to the end of the string, and the negative indices start from the end and go to the beginning of a string.
In this article, you will learn how to perform various operations related to substrings in Python.
How to Get the First n Characters of a String in Python
This example will show you how to slice the first 5 characters from the string.
string = "hello world" print(string[:5])
Here you define the stop index which is 5. The start index is by default 0.
How to Get the Middle Characters of a String via Python Substrings
This example will show you how to slice characters from index 3 to index 5 from the string.
string = "hello world" print(string[3:5])
How to Get the Last Character of a String in Python
To get the last character use the -1 index (negative index). Check out the following example:
string = "freecodecamp" print(string[-1])
How to Get the Last n Characters of a String in Python
In this example, you will slice the last 4 characters from the string. Here you use the negative index to start slicing from the end of the string.
string = "freecodecamp" print(string[-4:])
How to Slice the String with Steps via Python Substrings
You can slice the string with steps after indicating a start-index and stop-index. By default, the step is 1 but in the following example, the step size is 2.
string = "welcome to freecodecamp" print(string[::2])
The output will be ‘wloet fecdcm’ .
How to Check if a Substring is Present Within a String in Python
Sometimes you want to check if a substring is present in a string. The following example will validate if the substring ‘code’ is in the string:
substring = "code" string = "welcome to freecodecamp" print(substring in string)
If present, it will return True, otherwise False.
Here, the output will be True .
Another Way to Check if the Python Substring is Present in the String
You can use the find() method to check if a substring is present in the string.
Let’s check the following example:
substring = "zz" string = "hello world" print(string.find(substring))
If it’s available it returns the left-most index of the substring, otherwise it returns -1 (which means it’s not available).
Here the output is -1 , which means “zz” is not present in “hello world”.
How to Get the Character of a Given Index in a String in Python
You can choose to slice a specific character according to its index number.
string ="hello world" print(string[4])
How to Create a List of Substrings from a String in Python
You can use the split() method to create a list of substrings. Let’s check out the following example:
string = "welcome to freecodecamp platform" print(string.split())
The output will be [‘welcome’, ‘to’, ‘freecodecamp’, ‘platform’]
How to Reverse a String in Python with Negative Steps
To reverse the string, the step must be a negative value, for example -1.
string = "welcome to freecodecamp" print(string[::-1])
The output is ‘pmacedoceerf ot emoclew’ .
How to Count How Many Times a Substring is Present in a String in Python
You can use the count() method to know how many times a particular substring is in a string.
string = "we will have a quick coding lesson this afternoon" print(string.count('noon'))
Final Thoughts on Python Substrings
Congratulations 👏👏, you have made it to the end of this article! I hope you have learned something new about Python substrings.
If you learned something new or enjoyed reading this article, please share it so that others can see it. Until then, see you in the next post!
You can also find me on Twitter @Davis_McDavid.
And you can read more articles like this here
How to Substring a String in Python
Python offers many ways to substring a string. This is often called «slicing».
start : The starting index of the substring. The character at this index is included in the substring. If start 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. If end 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. If step is not included, it is assumed to be equal to 1.
Here’s an Interactive Scrim of How to Substring a String in Python
Basic Usage
string[start:end] : Get all characters from start to end — 1
string[:end] : Get all characters from the beginning of the string to end — 1
string[start:] : Get all characters from start to the end of the string
string[start:end:step] : Get all characters from start to end — 1, not including every step character
Examples
1. Get the first 5 characters of a string
string = "freeCodeCamp" print(string[0:5])
Note: print(string[:5]) returns the same result as print(string[0:5])
2. Get a substring 4 characters long, starting from the 3rd character of the string
string = "freeCodeCamp" print(string[2:6])
3. Get the last character of the string
string = "freeCodeCamp" print(string[-1])
Notice that the start or end 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 string
string = "freeCodeCamp" print(string[-5:])
5. Get a substring which contains all characters except the last 4 characters and the 1st character
string = "freeCodeCamp" print(string[1:-4])
6. Get every other character from a string
string = "freeCodeCamp" print(string[::2])