Signup/Sign In
LAST UPDATED: JUNE 24, 2023

Python String methods - split(), join() and replace()

Technology #python

    In my previous posts, we explored a bunch of string methods, like:

    Python String: isdigit(), isnumeric() and isdecimel()

    Python String: islower(), isupper() and isprintable()

    Python String: isalpha(), isalnum() and isascii()

    In today's post, we will continue with more string methods and understand the following methods:

    1. str.split

    2. str.join

    3. str.replace

    Without further delay, let's begin.


    Python String methods - split(), join() and replace()

    1. The split method

    Python's split method splits the given string based on a specific separator(which can be a character, symbol, or even empty space). It returns a list of substrings that are separated based on the given separator value.

    Syntax of split method:

    string.split(separator/specific value, max_splits)

    The split method takes two parameters. If both the parameters or one of them haven't been provided, the default value of the respective parameter is used. The separator/specific value informs where to split the string from. It behaves like a delimiter. If no value is provided for the separator, then by default whitespace is taken as the separator.

    The max_splits value tells the number of times the string needs to be split. If no value is provided, the split is done till the end of the string is encountered.

    Time for an example:

    my_string = 'Study Tonight'
    # No parameter is provided - takes default of separator as whitespace and max_splits as end of string
    split_string = (my_string.split())
    print(split_string)
    print(type(split_string))
    
    my_string = 'Study,Tonight'
    # The separator parameter is provided as, and max_splits as end of string by default
    split_string = (my_string.split(','))
    print(split_string)
    
    my_string = 'Study,Tonight has: 12 characters'
    # The separator parameter is provided as, and max_splits as end of string by default
    split_string = (my_string.split(':'))
    print(split_string)
    
    my_string = 'Study:Tonight has: 12 : characters'
    # The separator parameter is provided as, and max_splits is 3
    split_string = (my_string.split(':', 3))
    print(split_string)
    
    my_string = 'Study:Tonight has: 12 : characters'
    # The separator parameter is provided as, and max_splits is 0
    split_string = (my_string.split(':', 0))
    print(split_string)
    
    my_string = 'Study:Tonight has: 12 : characters'
    # The separator parameter is provided as , and max_splits is 2
    split_string = (my_string.split(':', 2))
    print(split_string)
    
    my_string = 'StudyTonight'
    print([my_string [i:i+5] for i in range(0, len(my_string), 5)])


    Output:

    ['Study', 'Tonight']
    <class 'list'>
    ['Study', 'Tonight']
    ['Study,Tonight has', ' 12 characters']
    ['Study', 'Tonight has', ' 12 ', ' characters']
    ['Study:Tonight has: 12 : characters']
    ['Study', 'Tonight has', ' 12 : characters']
    ['Study', 'Tonig', 'ht']


    2. The join method

    As the name suggests, it helps to join strings, i.e. this method helps combine or concatenate strings but not like the + operator. When we use the join method, it combines every element of the input iterable(that has the ability to be iterated through, for example: list, tuple, strings, set, dictionary, objects defined with __iter__ method or __getitem__ method and the elements should be of string type) with the calling string and returns a string.

    The element present in the iterable could also be an object which has the ability to return one of its members(which is of string type) at a time.

    Hence, it is a string method using which we can join a string to every element of an iterable or every character of another string.

    Syntax of join method:

    string.join(iterable)

    Note: If the value passed to the join method (the iterable) is not a string, or if we try to use the join method with a list of integers or nonstring type elements, we will get TypeError error..

    Time for an example:

    # Joining elements in a list based on a separator
    my_list = ['1', '2', '3', '4'] 
    seperator = '-\n'
    print(seperator.join(my_list))
    
    # Joining elements of a tuple based on a separator
    my_tuple = ('3', '7', '2', '0') 
    seperator = 'not'
    print(seperator.join(my_tuple))
    
    str_1 = 'abc'
    str_2 = '123'
    # Every character of str_2 is concatenated ahead of str_21
    print('str_1.join(str_2):', str_1.join(str_2)) 
    # Every character of str_1 is concatenated ahead of str_1
    print('str_2.join(str_1):', str_2.join(str_1)) 
    
    # Joining elements of a set
    my_set = {'Studytonight', '1.7', '3.95', 'Python'} 
    # Joining elements of a dictionary
    my_another_dict = {'Maths' : 1, 'Physics' : 2} 
    s = ',, '
    print(s.join(my_set))
    s = '__'
    print(s.join(my_another_dict))

    Output:

    1-
    2-
    3-
    4
    3not7not2not0
    str_1.join(str_2): 1abc2abc3
    str_2.join(str_1): a123b123c
    1.7,, Studytonight,, 3.95,, Python
    Maths__Physics


    What if I wish to join a non-string object to another?

    This results in a TypeError and it can be seen below:

    my_another_dict = {1: 'Maths', 2: 'Physics'}
    s = '()'
    print(s.join(my_another_dict))

    Output:

    Traceback (most recent call last):
    
      File "<ipython-input-16-071eb060bc84>", line 32, in <module>
        print(s.join(my_another_dict))
    
    TypeError: sequence item 0: expected str instance, int found


    3. The replace method

    The built-in replace method is used to replace the occurrences of a specific substring inside a string with another value. It returns another copy of the original string by replacing all occurrences of a specific substring with the specified value (or substring). The original string remains unaltered. If the value to be replaced is not found in the original string, a copy of the original string is returned.

    Syntax of replace method:

    string.replace(old_string, new_string, count)

    At maximum, the replace method takes 3 parameters:

    old_string: The original string whose substring needs to be replaced.

    new_string: The copy of old_string with the replaced substring.

    count: The number of times the substring needs to be replaced in the original string. This is an optional parameter, if not specified, it replaces all occurrences of the substring with the new value.

    Time for an example:

    # Replacing 0 occurances of substring in original string with new value
    my_str = 'Hello there, Studytonight says Hello'
    print (my_str.replace('Hello', 'Hi', 0))
    
    # Replacing 1 occurance of substring in original string with new value
    my_str = 'Hello there, Studytonight says Hello'
    print (my_str.replace('Hello', 'Hi', 1))
    
    # The value of count hasn't been specified, which means all occurrences are replaced
    my_str = 'I hope all is well in the well'
    print(my_str.replace('well', "great"))
    
    # Replacing specific character of a string with another character, where count isn't specified
    my_str = 'Stody, Stody tonight'
    print(my_str.replace('o', 'u'))

    Output:

    Hello there, Studytonight says Hello
    Hi there, Studytonight says Hello
    I hope all is great in the great
    Study, Study tunight


    Conclusion

    Python's split(), join(), and replace() string methods are powerful allies in your quest for efficient string manipulation. By mastering these techniques, you can effortlessly split strings into substrings, merge multiple strings into one, and replace specific patterns or characters within a string. These methods provide valuable functionality for data processing, text parsing, and content transformation.

    In this post, we understood the usage of string methods, namely: split, join and replace. These methods are essential in string mangling. By mastering these string methods, you can streamline your Python programming and make your code more efficient and readable. Try the below codes in your IDE and change the inputs to see how things vary.

    Frequently Asked Questions(FAQs)

    1. In Python, what is the divide() method?

    In Python, the split() method is a string function that enables you to divide a string into a collection of substrings depending on a delimiter.

    2. What is the Python combine() method?

    In Python, the join() method is a string method that enables you to merge a collection of strings into a single string, with each part split by a delimiter you specify.

    3. What is the Python substitute() method?

    In Python, the replace() method is a string function that enables you to change particular characters or substrings within a string with new ones.

    4. Can I use these string techniques on any length string?

    Yes, these string methods can be used on strings of any length and are particularly useful when dealing with large datasets or strings with multiple characters.

    You may also like:

    I love writing about Python and have more than 5 years of professional experience in Python development. I like sharing about various standard libraries in Python and other Python Modules.
    IF YOU LIKE IT, THEN SHARE IT
    Advertisement

    RELATED POSTS