Python solve problem with string operation

Denis McMahon denismfmcmahon at gmail.com
Thu Jan 16 19:30:16 EST 2014


On Fri, 17 Jan 2014 00:24:40 +0200, Nac Temha wrote:

> Hi everyone,
> 
> I want to do operation with chars in the given string. Actually I want
> to grouping the same chars.
> 
> For example;
> 
> input : "344111133311222223377"
> operation-> (3)(44)(1111)(333)(11)(22222)(33)(77)
> output: "34131237"

> How can I do without list, regular expression. just using string
> operations. Using an effective methods of python for this problem.

You can do it on one line, but it looks really messy:

output = ''.join([{x:input[x]for x in range(len(input))}[x]for x in range
(len({x:input[x]for x in range(len(input))}))if(x==0 or {x:input[x]for x 
in range(len(input))}[x-1]!={x:input[x]for x in range(len(input))}[x])])

It looks much better if you do it in steps:

a = {x:input[x]for x in range(len(input))}
b = [a[n]for n in range(len(a))if(n==0 or a[n-1]!=a[n])])
output = ''.join(b)

If you really want to do it using just 'string' ops:

for i in range(len(input)):
    if (i==0):
        output=input[0]
    elif input[i]!=input[i-1]:
        output+=input[i]

-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list