Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python | Split String and Get Last Element

#1
Python | Split String and Get Last Element

Rate this post

Summary: Use given_string.rsplit('sep', 1)[-1] to split the string and get the last element. Another approach is to use given_string.rpartition('sep', 1)[-1]

Minimal Solution:

dob = '21/08/2023'
# Method 1
print(dob.rsplit('/', 1)[-1])
# Method 2
print(dob.rpartition('/')[-1]) # OUTPUT: 2023

Problem Formulation


?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


# Input:
text = 'Java_C++_C#_Golang_Python'
# Expected Output:
Split String: ['Java_C++_C#_Golang', 'Python']
Last Element: Python

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


# Input:
text = 'Java_C++_C#_Golang_Python_'
# Expected Output:
Split String: ['Java_C++_C#_Golang', 'Python']
Last Element: Python

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 rsplit method splits a given string based on a given separator and stores the characters/substrings into a list. For example, finxterx42'.rsplit('x') will return the list ['fin', 'ter', '42'] as an output. rsplit can take two arguments –

  • sep – The separator string on which it is split.
  • maxsplit – The number of times the string is split.

Thus, you can use the maxsplit argument to your advantage and solve the given question by setting maxsplit = 1. 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 rsplit method.

Solution to Example 1:

text = 'Java_C++_C#_Golang_Python'
print("Split String: ", text.rsplit('_', 1))
print("Last Element: ", text.rsplit('_', 1)[-1])

Output:

Split String: ['Java_C++_C#_Golang', 'Python']
Last Element: Python

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 rsplit with the maxsplit argument will create a list that will create a list that will contain an empty character as the last item as shown below –


To avoid this problem, you can use the strip() function to get rid of the separator and then use rsplit as shown in the snippet below.

text = 'Java_C++_C#_Golang_Python_'
text = text.strip('_')
print("Split String: ", text.rsplit('_', 1))
print("Last Element: ", text.rsplit('_', 1)[-1])

Output:

Split String: ['Java_C++_C#_Golang', 'Python'] Last Element: Python

Method 2: Using rpartition


You can also use the rpartition method to solve the given problem. The rpartition 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: finxterx42'.rpartition('x') will return the following tuple: ('finxter', 'x', '42')

Thus, you can simply extract the last item from the tuple after the string has been cut by the rpartition method.

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:

Split String: ('Java_C++_C#_Golang', '_', 'Python')
Last Element: Python

✨Coding Challenge


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:

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 “.“. So, you can use rpartition and feed “.” as the separator and extract the last item (the network bit) from the tuple returned by the rpartition 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 bin function to generate the final output.

?Related Read: Python Print Binary Without ‘0b’

Conclusion


 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.

Recommended Reads:
⦿ How To Split A String And Keep The Separators?
⦿
 How To Cut A String In Python?
⦿ Python | Split String into Characters



https://www.sickgaming.net/blog/2022/11/...t-element/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python Int to String with Trailing Zeros xSicKxBot 0 32 12-01-2025, 05:47 PM
Last Post: xSicKxBot
  [Tut] Wrap and Truncate a String with Textwrap in Python xSicKxBot 0 2,053 09-01-2023, 07:45 PM
Last Post: xSicKxBot
  [Tut] Write a Long String on Multiple Lines in Python xSicKxBot 0 1,500 08-17-2023, 11:05 AM
Last Post: xSicKxBot
  [Tut] 5 Effective Methods to Sort a List of String Numbers Numerically in Python xSicKxBot 0 1,555 08-16-2023, 08:49 AM
Last Post: xSicKxBot
  [Tut] Sort a List, String, Tuple in Python (sort, sorted) xSicKxBot 0 1,694 08-15-2023, 02:08 PM
Last Post: xSicKxBot
  [Tut] F-String Python Hex, Oct, and Bin: Efficient Number Conversions xSicKxBot 0 1,666 03-28-2023, 12:01 PM
Last Post: xSicKxBot
  [Tut] How to Correctly Write a Raw Multiline String in Python: Essential Tips xSicKxBot 0 1,489 03-27-2023, 05:54 PM
Last Post: xSicKxBot
  [Tut] How To Extract Numbers From A String In Python? xSicKxBot 0 1,315 02-26-2023, 02:45 PM
Last Post: xSicKxBot
  [Tut] Python | Split String and Remove newline xSicKxBot 0 1,288 12-16-2022, 10:38 PM
Last Post: xSicKxBot
  [Tut] Python | Split Text into Sentences xSicKxBot 0 1,171 12-14-2022, 01:24 PM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016