Summary: You can use the split()
method to extract the head and tail elements from a given string.
Minimal Example
dob = '21/08/2023' head = dob.split('/')[0] tail = dob.split('/')[-1] print(f"Head: {head}\nTail: {tail}") head = dob.partition('/')[0] tail = dob.rpartition('/')[-1] print(f"Head: {head}\nTail: {tail}") # OUTPUTS: Head: 21 Tail: 2023
In the following articles, we have learned how to split a string and keep the first and last elements separately.
In this article, you will learn how to get the first element and the last element in the same script, i.e., “How to split a string and keep the head and tail elements?”
Problem Formulation
Problem: How to split a string and keep head and tail?
Example: Let’s try to understand the coding challenge with the help of an example.
# Input text = "Java_C++_C#_Golang_Python" # Output Head: Java Tail: Python
Note that the first element in the given string is “Java” while the last element is the string “Python”. So, these are the two elements that you need to extract from the given string.
Now that you have a clear picture of what the problem asks you to do, let us dive into the solutions straightaway.
Method 1: Using split
The easiest way to extract the head and tail of the given string is to first split the entire string into a list containing the split substrings. You can then extract the first and the last element from this list using their indices. The index of the first item/element will always be “0” while the last element can be acquired using its negative index, i.e., “-1”.
Code:
text = "Java_C++_C#_Golang_Python" head = text.split('_')[0] tail = text.split('_')[-1] print(f"Head: {head}\nTail: {tail}")
Output:
Head: Java Tail: Python
Reader’s Digest
split()
is a built-in function in Python that splits the string at a given separator and returns a split list of substrings.
Syntax: str.split(sep=None, maxsplit=-1)
- Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most
maxsplit+1
elements). If maxsplit is not specified or-1
, then there is no limit on the number of splits (all possible splits are made). - If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example,
'1,,2'.split(',')
returns['1', '', '2']
).
Method 2: Using partition and rpartition
Prerequisite:
- The
partition()
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. It then returns a tuple with the same three strings.
- The
rpartition()
searches for the last occurrence of the separator substring and returns a tuple with three strings:- (1) everything before the separator,
- (2) the separator itself, and
- (3) everything after it.
Approach: Thus, you can simply extract the first item from the tuple after the string has been cut by the partition
method. Similarly, you can extract the last item from the tuple after the string has been cut by the rpartition
method.
Code:
text = "Java_C++_C#_Golang_Python" head = text.partition('_')[0] tail = text.rpartition('_')[-1] print(f"Head: {head}\nTail: {tail}")
Output:
Head: Java Tail: Python
Conclusion
That was it for this short and important tutorial. I hope it helped you. Please subscribe and stay tuned for more interesting reads and solutions.
Check out my new Python book Python One-Liners (Amazon Link).
If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!
The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).
Publisher Link: https://nostarch.com/pythononeliners