Open In App

Python splitfields() Method

Last Updated : 17 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The splitfields() method is a user-defined method written in Python that splits any kind of data into a list of fields using a delimiter. The delimiter can be specified as an argument to the method, and if no delimiter is specified, the method splits the string using whitespace characters as the delimiter.

Syntax: string.splitfields(delimiter)

Parameters:

  • string (required) – The string to be split into fields.
  • delimiter (optional) – The character or string to use as the delimiter for splitting the string into fields. If this parameter is not specified, the method uses whitespace characters as the delimiter.

Return Value: The splitfields() method returns a list of fields that were separated by the specified delimiter. If no delimiter is specified, the method splits the string using whitespace characters. If the string is empty, the method returns an empty list.

Type Error: If you call the splitfields() method with the wrong number or type of arguments, you will get a TypeError. 

Examples of splitfields() Method

Let’s see some examples of how can a user-defined splitfields() Method can be implemented in Python.

Example 1: Using splitfields() with the wrong type of arguments

Python3




# Example of a TypeError when calling splitfields()
num = 123
fields = num.splitfields(",")


Output:

Since the splitfields() method can only be called on string objects, this will result in a TypeError. The error message will look something like this:

Traceback (most recent call last):
 File "<ipython-input-1-6b9c6a2fbfd8>", line 2, in <module>
   fields = num.splitfields(",")
AttributeError: 'int' object has no attribute 'splitfields'

Example 2: Using splitfields() with a String

Python3




class MyString(str):
    def splitfields(self, sep=None):
        if sep is None:
            return self.split()
        else:
            return self.split(sep)
  
# Splitting a string into fields using whitespace as delimiter
str1 = "The quick brown fox"
fields1 = MyString(str1).splitfields()
print(fields1)
  
  
# Splitting a string into fields using a specific delimiter
str2 = "apple,banana,orange"
fields2 = MyString(str2).splitfields(",")
print(fields2)


Output:

['The', 'quick', 'brown', 'fox']
['apple', 'banana', 'orange']

Example 3: Using splitfields() with a List

Python3




class MyString(str):
    def splitfields(self, sep=None):
        if sep is None:
            return self.split()
        else:
            return self.split(sep)
  
# Splitting a list into fields using whitespace as delimiter
lst1 = ["The", "quick", "brown", "fox"]
fields3 = MyString(" ".join(lst1)).splitfields()
print(fields3)
  
# Splitting a list into fields using a specific delimiter
lst2 = ["apple", "banana", "orange"]
fields4 = MyString(",".join(lst2)).splitfields(",")
print(fields4)


Output:

['The', 'quick', 'brown', 'fox']
['apple', 'banana', 'orange']

Example 4: Using splitfields() with a Set

Python3




class MyString(str):
    def splitfields(self, sep=None):
        if sep is None:
            return self.split()
        else:
            return self.split(sep)
  
class MySet(set):
    def splitfields(self, sep=None):
        str_set = " ".join(self)
        return MyString(str_set).splitfields(sep)
  
# Splitting a set into fields using whitespace as delimiter
set1 = {"The", "quick", "brown", "fox"}
fields5 = MySet(set1).splitfields()
print(fields5)
  
  
# Splitting a set into fields using a specific delimiter
set2 = {"apple", "banana", "orange"}
fields6 = MySet(set2).splitfields(",")
print(fields6)


Output:

['quick', 'brown', 'fox', 'The']
['apple banana orange'] 


Previous Article
Next Article

Similar Reads

Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
Class method vs Static method in Python
In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated after your function is defined. The result of that
4 min read
Difference between Method Overloading and Method Overriding in Python
Method Overloading: Method Overloading is an example of Compile time polymorphism. In this, more than one method of the same class shares the same method name having different signatures. Method overloading is used to add more to the behavior of methods and there is no need of more than one class for method overloading.Note: Python does not support
3 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
Pandas DataFrame interpolate() Method | Pandas Method
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Pandas DataFrame duplicated() Method | Pandas Method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas duplicated() method identifies duplicated rows in a DataFrame. It returns a boolean series which is True only for unique rows. Ex
3 min read
Python Dictionary get() Method
Python Dictionary get() Method return the value for the given key if present in the dictionary. If not, then it will return None (if get() is used with only one argument). Python Dictionary get() Method Syntax: Syntax : Dict.get(key, default=None) Parameters: key: The key name of the item you want to return the value fromValue: (Optional) Value to
2 min read
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Python | os._exit() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os._exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buff
2 min read
Python | os.WEXITSTATUS() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.WEXITSTATUS() method in Python is used to get the integer parameter used by a process in exit(2) system call if os.WIFEXITED(sta
3 min read
Practice Tags :
three90RightbarBannerImg