Reputation: 679
I want to create a list out of my string in python that would show me how many times a letter is shown in a row inside the string. for example:
my_string= "google"
i want to create a list that looks like this:
[['g', 1], ['o', 2], ['g', 1], ['l', 1], ['e', 1]]
Thanks!
Upvotes: 2
Views: 168
Reputation: 14271
You can use a regular expression and a dictionary to find and store the longest string of each letter like this
s = 'google'
nodubs = [s[0]] + [s[x] if s[x-1] != s[x] else '' for x in range(1,len(s))]
nodubs = ''.join(nodubs)
import re
dic = {}
for letter in set(s):
matches = re.findall('%s+' % letter, s)
longest = max([len(x) for x in matches])
dic[letter] = longest
print [[n,dic[n]] for n in nodubs]
Result:
[['g', 1], ['o', 2], ['g', 1], ['l', 1], ['e', 1]]
Upvotes: 0
Reputation: 304
You could use groupby from itertools:
from itertools import groupby
my_string= "google"
[(c, len(list(i))) for c, i in groupby(my_string)]
Upvotes: 8