Open In App

Python program to split and join a string

Last Updated : 18 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python program to Split a string based on a delimiter and join the string using another delimiter. Splitting a string can be quite useful sometimes, especially when you need only certain parts of strings. A simple yet effective example is splitting the First-name and Last-name of a person. Another application is CSV(Comma Separated Files). We use split to get data from CSV and join to write data to CSV. In Python, we can use the function split() to split a string and join() to join a string. For a detailed articles on split() and join() functions, refer these : split() in Python and join() in Python. Examples :

Split the string into list of strings

Input : Geeks for Geeks
Output : ['Geeks', 'for', 'Geeks']


Join the list of strings into a string based on delimiter ('-')

Input :  ['Geeks', 'for', 'Geeks']
Output : Geeks-for-Geeks

Below is Python code to Split and Join the string based on a delimiter : 

Python3




# Python program to split a string and 
# join it using different delimiter
 
def split_string(string):
 
    # Split the string based on space delimiter
    list_string = string.split(' ')
     
    return list_string
 
def join_string(list_string):
 
    # Join the string based on '-' delimiter
    string = '-'.join(list_string)
     
    return string
 
# Driver Function
if __name__ == '__main__':
    string = 'Geeks for Geeks'
     
    # Splitting a string
    list_string = split_string(string)
    print(list_string)
 
     # Join list of strings into one
    new_string = join_string(list_string)
    print(new_string)


Output

['Geeks', 'for', 'Geeks']
Geeks-for-Geeks

Method: In Python, we can use the function split() to split a string and join() to join a string. the split() method in Python split a string into a list of strings after breaking the given string by the specified separator. Python String join() method is a string method and returns a string in which the elements of the sequence have been joined by the str separator. 

Python3




# Python code
# to split and join given string
 
# input string
s = 'Geeks for Geeks'
# print the string after split method
print(s.split(" "))
# print the string after join method
print("-".join(s.split()))
 
 
# this code is contributed by gangarajula laxmi


Output

['Geeks', 'for', 'Geeks']
Geeks-for-Geeks

Time complexity: O(n), where n is the length of given string
Auxiliary space: O(n)

Method: Here is an example of using the re module to split a string and a for loop to join the resulting list of strings:

Python3




import re
 
def split_and_join(string):
    # Split the string using a regular expression to match any sequence of non-alphabetic characters as the delimiter
    split_string = re.split(r'[^a-zA-Z]', string)
 
    # Join the list of strings with a '-' character between them
    joined_string = ''
    for i, s in enumerate(split_string):
        if i > 0:
            joined_string += '-'
        joined_string += s
     
    return split_string, joined_string
 
# Test the function
string = 'Geeks for Geeks'
split_string, joined_string = split_and_join(string)
print(split_string)
print(joined_string)


Output

['Geeks', 'for', 'Geeks']
Geeks-for-Geeks

In the above code, we first imported the re (regular expression) module in order to use the split() function from it. We then defined a string s which we want to split and join using different delimiters.

To split the string, we used the split() function from the re module and passed it the delimiter that we want to use to split the string. In this case, we used a space character as the delimiter. This function returns a list of substrings, where each substring is a part of the original string that was separated by the delimiter.

To join the list of substrings back into a single string, we used a for loop to iterate through the list. For each substring in the list, we concatenated it to a new string called new_string using the + operator. We also added a hyphen between each substring, to demonstrate how to use a different delimiter for the join operation.

Finally, we printed both the split and joined versions of the string to the console. The output shows that the string was successfully split and joined using the specified delimiters.

Method: Using regex.findall() method

Here we are finding all the words of the given string as a list (splitting the string based on spaces) using regex.findall() method and joining the result to get the result with hyphen

Python3




# Python code
# to split and join given string
import re
# input string
s = 'Geeks for Geeks'
# print the string after split method
print(re.findall(r'[a-zA-Z]+', s))
# print the string after join method
print("-".join(re.findall(r'[a-zA-Z]+', s)))


Output

['Geeks', 'for', 'Geeks']
Geeks-for-Geeks

Time complexity: O(n), where n is the length of given string
Auxiliary space: O(n)
Method: Using re.split()

Algorithm:

  1. Import the re module for regular expression operations.
  2. Define a function named split_string that takes a string argument string.
  3. Split the input string string into a list of substrings using the re.split() function and a regular expression that matches one or more whitespace characters (\s+).
  4. Return the list of substrings.
  5. Define a function named join_string that takes a list of strings list_string.
  6. Join the input list of strings list_string into a single string using the str.join() method with a hyphen delimiter.
  7. Return the resulting string.
  8. In the main block of the code, define an input string string and call the split_string() function with string as argument to split the string into a list of substrings.
  9. Call the join_string() function with the resulting list of substrings to join them into a single string with hyphen delimiter.
  10. Print the resulting list of substrings and the final joined string.

Python3




import re
 
def split_string(string):
    list_string = re.split('\s+', string)
    return list_string
 
def join_string(list_string):
    new_string = '-'.join(list_string)
    return new_string
 
if __name__ == '__main__':
    string = 'Geeks for Geeks'
     
    # Splitting a string
    list_string = split_string(string)
    print(list_string)
 
     # Join list of strings into one
    new_string = join_string(list_string)
    print(new_string)
#This code is contributed by Vinay Pinjala.


Output

['Geeks', 'for', 'Geeks']
Geeks-for-Geeks

Time complexity:
The time complexity of the split_string() function is O(n), where n is the length of the input string string, because the re.split() function performs a linear scan of the string to find whitespace characters and then splits the string at those positions.

The time complexity of the join_string() function is O(n), where n is the total length of the input list of strings list_string, because the str.join() method iterates over each string in the list and concatenates them with a hyphen delimiter.

Auxiliary Space:
The space complexity of the code is O(n), where n is the length of the input string string, because the split_string() function creates a new list of substrings that is proportional in size to the input string, and the join_string() function creates a new string that is also proportional in size to the input list of substrings.

Method: Using the find() method to find the index of the next space character

  • Initialize the input string to “Geeks for Geeks”.
  • Create an empty list called words to hold the words extracted from the input string.
  • Add the word up to the space to the words list.
  • Remove the word up to the space (including the space itself) from the input string.
  • Join the words list with the ‘-‘ separator to create a string with hyphens between each word, and assign it to the joined_string variable.
  • Print the resulting string with hyphens between each word.

Python3




#initialize the input string
s = 'Geeks for Geeks'
 
#create an empty list to hold the words
words = []
 
#loop through the string until no more spaces are found
while True:
    # find the index of the next space in the string
    space_index = s.find(' ')
    # if no more spaces are found, add the remaining string to the words list and break the loop
    if space_index == -1:
        words.append(s)   
        break
    # otherwise, add the word up to the space to the words list and remove it from the string
    words.append(s[:space_index])
    s = s[space_index+1:]
 
#join the words list with '-' and print the resulting string
joined_string = '-'.join(words)
print(joined_string)


Output

Geeks-for-Geeks

The time complexity of this code is O(n), where n is the length of the input string s
The space complexity is also O(n), since we are storing the list of words in memory, 



Similar Reads

Python | Pandas str.join() to join string/list elements with passed delimiter
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 str.join() method is used to join all elements in list present in a series with passed delimiter. Since strings are also array of
2 min read
Python Pandas - Difference between INNER JOIN and LEFT SEMI JOIN
In this article, we see the difference between INNER JOIN and LEFT SEMI JOIN. Inner Join An inner join requires two data set columns to be the same to fetch the common row data values or data from the data table. In simple words, and returns a data frame or values with only those rows in the data frame that have common characteristics and behavior
3 min read
PySpark Join Types - Join Two DataFrames
In this article, we are going to see how to join two dataframes in Pyspark using Python. Join is used to combine two or more dataframes based on columns in the dataframe. Syntax: dataframe1.join(dataframe2,dataframe1.column_name == dataframe2.column_name,"type") where, dataframe1 is the first dataframedataframe2 is the second dataframecolumn_name i
13 min read
Outer join Spark dataframe with non-identical join column
In PySpark, data frames are one of the most important data structures used for data processing and manipulation. The outer join operation in PySpark data frames is an important operation to combine data from multiple sources. However, sometimes the join column in the two DataFrames may not be identical, which may result in missing values. In this a
4 min read
Python | Pandas Split strings into two List/Columns using str.split()
Pandas provide a method to split string around a passed separator/delimiter. After that, the string can be stored as a list in a series or it can also be used to create multiple column data frames from a single separated string. It works similarly to Python's default split() method but it can only be applied to an individual string. Pandas <code
4 min read
Minimum length of a rod that can be split into N equal parts that can further be split into given number of equal parts
Given an array arr[] consisting of N positive integers, the task is to find the minimum possible length of a rod that can be cut into N equal parts such that every ith part can be cut into arr[i] equal parts. Examples: Input: arr[] = {1, 2}Output: 4Explanation:Consider the length of the rod as 4. Then it can be divided in 2 equal parts, each having
7 min read
Python String Methods | Set 2 (len, count, center, ljust, rjust, isalpha, isalnum, isspace & join)
Some of the string methods are covered in the set 3 below String Methods Part- 1 More methods are discussed in this article 1. len() :- This function returns the length of the string. 2. count("string", beg, end) :- This function counts the occurrence of mentioned substring in whole string. This function takes 3 arguments, substring, beginning posi
4 min read
Join Elements of a Set into a String in Python
You might have encountered situations where you needed to join the elements of a set into a string by concatenating them, which are separated by a particular string separator. Let's say we want to convert the set {"GFG", "courses", "are", "best"} into a string with a space between each element that results in "GFG courses are best". In this article
4 min read
Python String join() Method
Python join() is an inbuilt string function used to join elements of a sequence separated by a string separator. This function joins elements of a sequence and makes it a string. Python String join() SyntaxSyntax: separator_string.join(iterable) Parameters: Iterable - objects capable of returning their members one at a time. Some examples are List,
3 min read
Python Program to perform cross join in Pandas
In Pandas, there are parameters to perform left, right, inner or outer merge and join on two DataFrames or Series. However there's no possibility as of now to perform a cross join to merge or join two methods using how="cross" parameter. Cross Join : Example 1: The above example is proven as follows # importing pandas module import pandas as pd # D
3 min read
Practice Tags :
three90RightbarBannerImg