Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine similar characters in a list?

Tags:

python

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!

like image 765
Greg Avatar asked Feb 09 '19 04:02

Greg


People also ask

How do you combine characters in a list?

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.

How do I make a list of characters 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.

How do you add characters together in Python?

Python string object is immutable. So every time we use + operator to concatenate two strings, a new string is created.

How do you append a list of strings in Python?

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.


2 Answers

Try:

splitter = re.split("(#+)", test)
like image 168
mingganz Avatar answered Oct 02 '22 20:10

mingganz


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', '##']
like image 44
Ajax1234 Avatar answered Oct 02 '22 18:10

Ajax1234