Python program to split and join a string
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) |
['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 |
['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) |
['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))) |
['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:
- Import the re module for regular expression operations.
- Define a function named split_string that takes a string argument string.
- 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+).
- Return the list of substrings.
- Define a function named join_string that takes a list of strings list_string.
- Join the input list of strings list_string into a single string using the str.join() method with a hyphen delimiter.
- Return the resulting string.
- 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.
- Call the join_string() function with the resulting list of substrings to join them into a single string with hyphen delimiter.
- 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. |
['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) |
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,
Please Login to comment...