The Wayback Machine - https://web.archive.org/web/20240913172416/https://www.geeksforgeeks.org/python-program-split-join-string/
Open In App

Python program to split and join a string

Last Updated : 18 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Easy
57.29%
15.2K

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 program to split the string and convert it to dictionary
Given a delimiter (denoted as delim in code) separated string, order the splits in form of dictionary. Examples: Input : test_str = 'gfg*is*best*for*geeks', delim = “*” Output : {0: 'gfg', 1: 'is', 2: 'best', 3: 'for', 4: 'geeks'} Input : test_str = 'gfg*is*best', delim = “*” Output : {0: 'gfg', 1: 'is', 2: 'best'} Method 1 : Using split() + loop T
4 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,
5 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
Python Program to Join Equi-hierarchy Strings
Given a list of strings with several hierarchies, the task is to write a python program to join those which have the same hierarchies. Elements in the same dimension before a dimension change are known to be in the same hierarchy. Input : test_list = ["gfg ", " best ", [" for ", " all "], " all ", [" CS " , " geeks "]] Output : ['gfg best ', [' for
4 min read
Python program to split a string by the given list of strings
Given a list of strings. The task is to split the string by the given list of strings. Input : test_str = 'geekforgeeksbestforgeeks', sub_list = ["best"] Output : ['geekforgeeks', 'best', 'forgeeks'] Explanation : "best" is extracted as different list element. Input : test_str = 'geekforgeeksbestforgeeksCS', sub_list = ["best", "CS"] Output : ['gee
4 min read
Python Program to split string into k sized overlapping strings
Given a string, the task is to write a Python program to extract overlapping consecutive string slices from the original string according to size K. Example: Input : test_str = 'Geeksforgeeks', K = 4 Output : ['Geek', 'eeks', 'eksf', 'ksfo', 'sfor', 'forg', 'orge', 'rgee', 'geek', 'eeks'] Explanation : Consecutive overlapping 4 sized strings are ou
4 min read
numpy string operations | join() function
numpy.core.defchararray.join(sep, arr) is another function for doing string operations in numpy. For each element in arr, it returns a copy of the string in which the string elements of array have been joined by separator. Parameters: sep : It joins elements with the string between them. arr :Input array. Returns : Output array of str or unicode wi
1 min read
Split the string into minimum parts such that each part is in the another string
Given two strings A and B, the task is to split the string A into the minimum number of substrings such that each substring is in the string B. Note: If there is no way to split the string, then print -1 Examples: Input: A = "abcdab", B = "dabc" Output: 2 Explanation: The two substrings of A which is also present in B are - {"abc", "dab"} Input: A
11 min read
Python | Merge, Join and Concatenate DataFrames using Pandas
A dataframe is a two-dimensional data structure having multiple rows and columns. In a Pandas DataFrame, the data is aligned in the form of rows and columns only. A dataframe can perform arithmetic as well as conditional operations. It has a mutable size. This article will show how to join, concatenate, and merge in Pandas. Python Merge, Join, and
4 min read
Python | Split strings and digits from string list
Sometimes, while working with String list, we can have a problem in which we need to remove the surrounding stray characters or noise from list of digits. This can be in form of Currency prefix, signs of numbers etc. Let's discuss a way in which this task can be performed. Method #1 : Using list comprehension + strip() + isdigit() + join() The comb
5 min read
Split and Parse a string in Python
In Python, working with strings is a fundamental aspect of programming. Strings are sequences of characters and often contain structured data that needs to be processed or analyzed. The common operations performed on strings are splitting and parsing. Splitting a String in PythonIn Python, you can split a string into smaller parts using the split()
5 min read
How to split a string in C/C++, Python and Java?
Splitting a string by some delimiter is a very common task. For example, we have a comma-separated list of items from a file and we want individual items in an array. Almost all programming languages, provide a function split a string by some delimiter. In C: // Splits str[] according to given delimiters.// and returns next token. It needs to be ca
7 min read
Python Program to Split the array and add the first part to the end
There is a given array and split it from a specified position, and move the first part of the array add to the end. Examples: Input : arr[] = {12, 10, 5, 6, 52, 36} k = 2 Output : arr[] = {5, 6, 52, 36, 12, 10} Explanation : Split from index 2 and first part {12, 10} add to the end .Input : arr[] = {3, 1, 2} k = 1 Output : arr[] = {1, 2, 3} Explana
5 min read
Python Program to Split the Even and Odd elements into two different lists
In this program, a list is accepted with a mixture of odd and even elements and based on whether the element is even or odd, it is Split the Even and Odd elements using Python. Examples Input: [8, 12, 15, 9, 3, 11, 26, 23]Output: Even lists: [8, 12, 26] Odd lists: [15, 9, 3, 11, 23]Input: [2, 5, 13, 17, 51, 62, 73, 84, 95]Output: Even lists: [2, 62
2 min read
Python | Join tuple elements in a list
Nowadays, data is something that is the backbone of any Machine Learning technique. The data can come in any form and its sometimes required to be extracted out to be processed. This article deals with the issue of extracting information that is present in tuples in list. Let's discuss certain ways in which this can be performed. Method #1: Using j
6 min read
Python | Ways to join pair of elements in list
Given a list, the task is to join a pair of elements of the list. Given below are a few methods to solve the given task. Method #1: Using zip() method C/C++ Code # Python code to demonstrate # how to join pair of elements of list # Initialising list ini_list = ['a', 'b', 'c', 'd', 'e', 'f'] # Printing initial list print ("Initial list&
2 min read
Python | Join cycle in list
Sometimes, while dealing with graph problems in competitive programming, we have a list of pairs and we need to find if there is a possible cycle in it, and print all the elements in that cycle. Let's discuss certain way in which this problem can be tackled. Method 1: Using yield + loop + generator The brute method to perform is to use a generator
3 min read
Python - Consecutive K elements join in List
Sometimes, while working with Python lists, we can have a problem in which we need to join every K character into one collection. This type of application can have use cases in many domains like day-day and competitive programming. Let us discuss certain ways in which this task can be performed. Method #1: Using List comprehension This is one of th
4 min read
Python MySQL - Join
A connector is employed when we have to use mysql with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. Python-MySQL-Connector This is a MySQL Connector that allows Python to access MySQL Driv
2 min read
Python - Join Tuples to Integers in Tuple List
Sometimes, while working with Python records, we can have a problem in which we need to concatenate all the elements, in order, to convert elements in tuples in List to integer. This kind of problem can have applications in many domains such as day-day and competitive programming. Let's discuss certain ways in which this task can be performed. Inpu
5 min read
Python - Join Tuples if similar initial element
Sometimes, while working with Python tuples, we can have a problem in which we need to perform concatenation of records from the similarity of initial element. This problem can have applications in data domains such as Data Science. Let's discuss certain ways in which this task can be performed. Input : test_list = [(5, 6), (5, 7), (5, 8), (6, 10),
8 min read
Python - Cross Join every Kth segment
Given two lists, extract alternate elements at every Kth position. Input : test_list1 = [4, 3, 8, 2, 6, 7], test_list2 = [5, 6, 7, 4, 3, 1], K = 3 Output : [4, 3, 8, 5, 6, 7, 2, 6, 7, 4, 3, 1] Explanation : 4, 3, 8 after that 5, 6 from other list are extracted, and so on.Input : test_list1 = [4, 3, 8, 2], test_list2 = [5, 6, 7, 4], K = 2 Output : [
6 min read
Practice Tags :