The task is to split a string into parts based on a delimiter and then join those parts with a different separator.For example, "Hello, how are you?" split by spaces and joined with hyphens becomes: "Hello,-how-are-you?".
Let’s explore multiple methods to split and join a string in Python.
Using split() and join()
split() function divides the string into a list of words andjoin() reassembles them with a specified separator.
Pythona="Hello, how are you?"b=a.split()# Split by spacec="-".join(b)# Join with hyphenprint(b)print(c)
Output['Hello,', 'how', 'are', 'you?']Hello,-how-are-you?
Explanation:
- split()divides the string into a list of words, split by spaces by default.
- "-".join(b) reassembles the list into a string with hyphens between the words.
Using re.split() and '-'.join()
In cases needing advanced splitting e.g., handling multiple spaces or different delimiters, re.split() from the re module offers more flexibility. However, it’s less efficient than split() for simple cases due to the overhead of regular expression processing.
Pythonimportrea="Hello, how are you?"b=re.split(r'\s+',a)# Split by spacesc="-".join(b)# Join with a hyphenprint(b)print(c)
Output['Hello,', 'how', 'are', 'you?']Hello,-how-are-you?
Explanation:
- re.split(r'\s+', a) split the string by one or more spaces, providing more flexibility for advanced splitting.
- "-".join(b) joins the list of words with hyphens.
Using list comprehension with split()
This method splits the string withsplit() and uses a list comprehension to process or filter the list. While more compact and readable, it adds an extra step, reducing efficiency compared to usingsplit() and join() directly.
Pythona="Hello, how are you?"b=[wordforwordina.split()]# Split by spacec="-".join(b)# Join with a hyphenprint(b)print(c)
Output['Hello,', 'how', 'are', 'you?']Hello,-how-are-you?
Explanation:
- [word for word in a.split()]splits a by spaces into a list of words .
- "-".join(b)joins the words inb with hyphens.
Using str.partition() and str.replace()
This method splits the string manually usingpartition(), iterating over it to separate head and tail parts. After splitting,replace() or manual manipulation joins the parts. While functional, it’s less efficient due to multiple iterations and extra logic.
Pythona="Hello, how are you?"words,rem=[],awhilerem:head,_,rem=rem.partition(" ")ifhead:words.append(head)c="-".join(words)# Join with hyphenprint(words)print(c)Output['Hello,', 'how', 'are', 'you?']Hello,-how-are-you?
Explanation:
- partition(" ")splits the string into three parts, before the first space (head), the space itself (sep) and after the space (tail). This process repeats until the string is fully split.
- Loop ensures all words are extracted and added to the list words.
Related Articles
Program to split and join a string
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice