Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to split a string and join with comma
Sometimes we need to split a string into individual words and then join them back together with commas instead of spaces. Python provides simple built-in methods to accomplish this task efficiently.
So, if the input is like s = "Programming Python Language Easy Funny", then the output will be Programming, Python, Language, Easy, Funny
Algorithm
To solve this, we will follow these steps −
words − Create a list of words by applying
split()function on the string with delimiter " " (space)result − Join each item present in words and place ", " in between each pair of words using
join()Return the result
Example
Let us see the following implementation to get better understanding −
def solve(s):
words = s.split(' ')
result = ', '.join(words)
return result
s = "Programming Python Language Easy Funny"
print(solve(s))
The output of the above code is −
Programming, Python, Language, Easy, Funny
Using Default split()
We can also use split() without any parameter, which splits on any whitespace −
def solve_default(s):
words = s.split() # splits on any whitespace
result = ', '.join(words)
return result
s = "Programming Python Language Easy Funny"
print(solve_default(s))
Programming, Python, Language, Easy, Funny
One-Line Solution
For a more concise approach, we can combine both operations in a single line −
s = "Programming Python Language Easy Funny" result = ', '.join(s.split()) print(result)
Programming, Python, Language, Easy, Funny
How It Works
The split() method breaks the string at each space character and returns a list of words. The join() method then concatenates all elements in the list using the specified separator (", " in our case).
Conclusion
Use split() to break strings into words and join() to combine them with custom separators. The one-line approach ', '.join(s.split()) is the most Pythonic solution for this task.
