Python program to split and join a string
In Python, we can use the function split() to split a string and join() to join a string. These functions allow us to easily break a string into smaller parts and then reassemble those parts into a new string. This article will explore ways to split and join a string.
a = "Hello, how are you?"
# Split into words
words = a.split()
# Join with a hyphen
b = "-".join(words)
print(b )
Output
Hello,-how-are-you?
Split the string into a list of strings
Splitting a string can be quite useful sometimes, especially when we need only certain parts of strings. We can do this by using below mentioned methods.
Using string.split( )
split() method splits a string into a list of substrings based on a specified delimiter (by default, it splits by whitespace).
a = "Geeks,for,Geeks"
# Split by comma
b = a.split(",")
print(b)
Output
['Geeks', 'for', 'Geeks']
Using splitlines( )
The splitlines() method splits the string at line breaks and returns a list of lines. This is useful while using multiple strings.
a = "Geeks\nfor\nGeeks"
# multiline string
result = a.splitlines()
print(result)
Output
['Geeks', 'for', 'Geeks']
Join the list of strings into a string
After splitting a string into smaller parts, we might want to join those parts back together. This is commonly done with a delimiter between the parts.
Using join() method
The most common and efficient way to join a list of strings with a delimiter is using the join() method. This method is available for strings and allows we to specify the delimiter we want to use between elements.
a = ['Geeks', 'for', 'Geeks']
# Join with a space
result = " ".join(a)
print(result)
us
Output
Geeks for Geeks
Using for loop [Less Efficient]
Although less efficient, we can manually join the strings in a list using a for loop. This method allows we to apply more complex transformations during the joining process.
a = ['Geeks', 'for', 'Geeks']
# Manually join strings with a space
# (less efficient, but illustrative)
result = ""
for i, word in enumerate(a):
result += word
# Add space between words except at the end
if i < len(a) - 1:
result += " "
print(result)
Output
Geeks for Geeks