How to Split and Keep Delimiter on the Same Line in Python?

Estimated read time 1 min read

You can split a string in Python and keep the delimiter on the same line using the split() method and string concatenation. Here’s an example:

my_string = "Hello,world,how,are,you"
delimiter = ","

# Split the string
my_list = my_string.split(delimiter)

# Join the split strings back together with the delimiter
new_string = delimiter.join([word + delimiter for word in my_list])

print(new_string)  # Output: Hello,world,how,are,you,

In the code above, the split() method is used to split the my_string variable into a list of strings, with the delimiter “,”. Then, a list comprehension is used to iterate over each word in the list and add the delimiter to the end of it. Finally, the join() method is used to join the modified list of strings back together with the delimiter, and the resulting string is printed to the console.

Note that the last element in the resulting string will also have the delimiter at the end, since we added it to every element. If you don’t want this behavior, you can simply remove the last character from the resulting string.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply