What Is The Split(), Join(), Sub(), And Subn() Method In Python?

What Is The Split(), Join(), Sub(), And Subn() Method In Python?

Published on October 09 2023

In this tutorial, we will learn about Python split(), join(), sub(), and subn() methods and their examples in detail. This tutorial is part of Python's top 25 most commonly asked interview questions.

Using String

  • split() - function to split a string based on a delimiter to a list of strings.
# Syntax
string.split(delimiter, max)

Where:
   delimiter: is the character based on which the string is split. By default it is space.
   max: is the maximum number of splits
  • join() - to join a list of strings based on a delimiter to give a single string.

Using Regex

  • belong to the Python RegEx or ‘re module’ and are used to modify strings.
  • Methods
    • re.split() - uses a regex pattern to “split” a given string into a list
    • re.sub() - finds all substrings where the regex pattern matches and then replace them with a different string
    • re.subn() - This method is similar to the sub() method, but it returns the new string, along with the number of replacements.

Example - Split()

x= "The Programming Portal"
split_data = x.split()
print(split_data)

Output

[‘The’, ‘Programming’, ‘Portal’]

Example - Join()

split_data = [‘The’, ‘Programming’, ‘Portal’]
print(‘ ‘.join(split_data))

Output - Join()

The Programming Portal

To know about it, please refer to the official documentation website - official website.