Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #64118

Re: Python solve problem with string operation

From Denis McMahon <denismfmcmahon@gmail.com>
Newsgroups comp.lang.python
Subject Re: Python solve problem with string operation
Date 2014-01-17 00:30 +0000
Organization A noiseless patient Spider
Message-ID <lb9tio$7p1$4@dont-email.me> (permalink)
References <mailman.5607.1389911083.18130.python-list@python.org>

Show all headers | View raw


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@gmail.com

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Python solve problem with string operation Nac Temha <naccttemha@gmail.com> - 2014-01-17 00:24 +0200
  Re: Python solve problem with string operation John Gordon <gordon@panix.com> - 2014-01-16 22:30 +0000
    Re: Python solve problem with string operation Mark Lawrence <breamoreboy@yahoo.co.uk> - 2014-01-16 22:48 +0000
      Re: Python solve problem with string operation John Gordon <gordon@panix.com> - 2014-01-16 22:58 +0000
  Re: Python solve problem with string operation giacomo boffi <pecore@pascolo.net> - 2014-01-17 01:17 +0100
    Re: Python solve problem with string operation giacomo boffi <pecore@pascolo.net> - 2014-01-17 01:38 +0100
  Re: Python solve problem with string operation Denis McMahon <denismfmcmahon@gmail.com> - 2014-01-17 00:30 +0000
  Re: Python solve problem with string operation "Rhodri James" <rhodri@wildebst.org.uk> - 2014-01-17 01:05 +0000
  Re: Python solve problem with string operation Asaf Las <roegltd@gmail.com> - 2014-01-16 17:36 -0800

csiph-web