I'm trying to combine similar characters that are next to each other that are in a list. I was wondering if there was a Python way to do it? Here's an example:
test = 'hello###_world###test#test123##'
splitter = re.split("(#)", test)
splitter = filter(None, splitter)
Which returns this in the splitter variable:
['hello', '#', '#', '#', '_world', '#', '#', '#', 'test', '#', 'test123', '#', '#']
I'm trying to combine the hashes so the list turns into this:
['hello', '###', '_world', '###', 'test', '#', 'test123', '##']
Thanks for any help!
Use str. join() to convert a list of characters into a string. Call str. join(iterable) with the empty string "" as str and a list as iterable to join each character into a string.
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
Python string object is immutable. So every time we use + operator to concatenate two strings, a new string is created.
You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.
Try:
splitter = re.split("(#+)", test)
You can use itertools.groupby
:
import itertools
test = 'hello###_world###test#test123##'
new_result = [''.join(b) for _, b in itertools.groupby(test, key=lambda x:x == '#')]
Output:
['hello', '###', '_world', '###', 'test', '#', 'test123', '##']
You can also use re.findall
:
import re
result = re.findall('#+|[^#]+', test)
Output:
['hello', '###', '_world', '###', 'test', '#', 'test123', '##']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With