11-07-2022, 11:10 PM
Python | Split String and Get Last Element
Rate this post
Summary: Use to split the string and get the last element. Another approach is to use
Minimal Solution:
[b]Problem Formulation[/b]
Problem: Given a string. How will you split the string and get the last element?
Let’s try to understand the given problem with the help of an example:
Example 1
In the above example, “” is the separator. However, not the entire string has been split. Only the last substring that comes after the separator has been extracted.
Example 2
Unlike the previous example, the input string ends with the separator itself. However, the output is similar. So, you have a different input string, but you have to generate a similar output by eliminating the separator.
Let’s dive into the different ways of solving the given problems.
Method 1: Using rsplit
Prerequisite: Simply put, the method splits a given string based on a given separator and stores the characters/substrings into a list. For example, will return the list as an output. can take two arguments –
Thus, you can use the argument to your advantage and solve the given question by setting . This means the string will be split along the specified separator only once from the right end. Once the string is split into two parts from the right end, all that you need to do is extract the second element from the list created by the method.
Solution to Example 1:
Output:
Solution to Example 2: In the second scenario, you must get rid of the separator that comes at the end of the string. Otherwise, simply using with the argument will create a list that will create a list that will contain an empty character as the last item as shown below –
![[Image: image-61-1024x142.png]](https://blog.finxter.com/wp-content/uploads/2022/11/image-61-1024x142.png)
To avoid this problem, you can use the strip() function to get rid of the separator and then use as shown in the snippet below.
Output:
Method 2: Using rpartition
You can also use the method to solve the given problem. The method searches for a separator substring and returns a tuple with three strings: (1) everything before the separator, (2) the separator itself, and (3) everything after it. For example: will return the following tuple:
Thus, you can simply extract the last item from the tuple after the string has been cut by the method.
Code:
Output:
[b]Coding Challenge[/b]
Before we wrap up this tutorial, here’s a coding challenge for you to test your grip on the concept you just learned.
Input: Consider the following IP Address –
ip = 110.210.130.140
Challenge: Extract the network bit from the given class A ip address and convert it to its binary form.
Expected Output:
10001100
Hint:
– 140 is the network bit!
– How to Convert a String to Binary in Python?
Solution:
Explanation: The solution is pretty straightforward. You first have to extract the network bit, i.e., 140. This happens to be the last item after the ““. So, you can use and feed “.” as the separator and extract the last item (the network bit) from the tuple returned by the method. Since this will be a string, you must convert it to an integer and then typecast this integer to a binary number using the function to generate the final output.
Related Read: Python Print Binary Without ‘0b’
[b]Conclusion[/b]
I hope you enjoyed the numerous scenarios and challenges used in this tutorial to help you learn the two different ways of splitting a string and getting the last item. Please subscribe and stay tuned for more interesting tutorials and solutions.
[b]Recommended Reads:
⦿ How To Split A String And Keep The Separators?⦿ How To Cut A String In Python?⦿ Python | Split String into Characters[/b]
Rate this post
Summary: Use
Code:
given_string.rsplit('sep', 1)[-1]Code:
given_string.rpartition('sep', 1)[-1]Minimal Solution:
Code:
dob = '21/08/2023'
# Method 1
print(dob.rsplit('/', 1)[-1])
# Method 2
print(dob.rpartition('/')[-1]) # OUTPUT: 2023[b]Problem Formulation[/b]
Problem: Given a string. How will you split the string and get the last element?Let’s try to understand the given problem with the help of an example:
Example 1
Code:
# Input:
text = 'Java_C++_C#_Golang_Python'
# Expected Output:
Split String: ['Java_C++_C#_Golang', 'Python']
Last Element: PythonIn the above example, “
Code:
_Example 2
Code:
# Input:
text = 'Java_C++_C#_Golang_Python_'
# Expected Output:
Split String: ['Java_C++_C#_Golang', 'Python']
Last Element: PythonUnlike the previous example, the input string ends with the separator itself. However, the output is similar. So, you have a different input string, but you have to generate a similar output by eliminating the separator.
Let’s dive into the different ways of solving the given problems.
Method 1: Using rsplit
Prerequisite: Simply put, the
Code:
rsplitCode:
finxterx42'.rsplit('x')Code:
['fin', 'ter', '42']Code:
rsplit- – The separator string on which it is split.Code:
sep
- – The number of times the string is split.Code:
maxsplit
Thus, you can use the
Code:
maxsplitCode:
maxsplit = 1Code:
rsplitSolution to Example 1:
Code:
text = 'Java_C++_C#_Golang_Python'
print("Split String: ", text.rsplit('_', 1))
print("Last Element: ", text.rsplit('_', 1)[-1])Output:
Code:
Split String: ['Java_C++_C#_Golang', 'Python']
Last Element: PythonSolution to Example 2: In the second scenario, you must get rid of the separator that comes at the end of the string. Otherwise, simply using
Code:
rsplitCode:
maxsplit![[Image: image-61-1024x142.png]](https://blog.finxter.com/wp-content/uploads/2022/11/image-61-1024x142.png)
To avoid this problem, you can use the strip() function to get rid of the separator and then use
Code:
rsplitCode:
text = 'Java_C++_C#_Golang_Python_'
text = text.strip('_')
print("Split String: ", text.rsplit('_', 1))
print("Last Element: ", text.rsplit('_', 1)[-1])Output:
Code:
Split String: ['Java_C++_C#_Golang', 'Python'] Last Element: PythonYou can also use the
Code:
rpartitionCode:
rpartitionCode:
finxterx42'.rpartition('x')Code:
('finxter', 'x', '42')Thus, you can simply extract the last item from the tuple after the string has been cut by the
Code:
rpartitionCode:
Code:
# Solution to Example 1
text = 'Java_C++_C#_Golang_Python'
print("Split String: ", text.rpartition('_'))
print("Last Element: ", text.rpartition('_')[-1]) # Solution to Example 2
text = 'Java_C++_C#_Golang_Python_'
text = text.strip('_')
print("Split String: ", text.rpartition('_'))
print("Last Element: ", text.rpartition('_')[-1])Output:
Code:
Split String: ('Java_C++_C#_Golang', '_', 'Python')
Last Element: Python
[b]Coding Challenge[/b]Before we wrap up this tutorial, here’s a coding challenge for you to test your grip on the concept you just learned.
Input: Consider the following IP Address –
ip = 110.210.130.140
Challenge: Extract the network bit from the given class A ip address and convert it to its binary form.
Expected Output:
10001100
Hint:– 140 is the network bit!
– How to Convert a String to Binary in Python?
Solution:
Code:
ip = '110.210.130.140'
nw_bit = int(ip.rpartition('.')[-1])
print(bin(nw_bit)[2:])Explanation: The solution is pretty straightforward. You first have to extract the network bit, i.e., 140. This happens to be the last item after the “
Code:
.Code:
rpartitionCode:
rpartitionCode:
bin
Related Read: Python Print Binary Without ‘0b’[b]Conclusion[/b]
I hope you enjoyed the numerous scenarios and challenges used in this tutorial to help you learn the two different ways of splitting a string and getting the last item. Please subscribe and stay tuned for more interesting tutorials and solutions.
[b]Recommended Reads:
⦿ How To Split A String And Keep The Separators?⦿ How To Cut A String In Python?⦿ Python | Split String into Characters[/b]

