Connecting Tech Pros Worldwide Help | Site Map

alternating string replace

cesco
Guest
 
Posts: n/a
#1: Jan 9 '08
Hi,

say I have a string like the following:
s1 = 'hi_cat_bye_dog'
and I want to replace the even '_' with ':' and the odd '_' with ','
so that I get a new string like the following:
s2 = 'hi:cat,bye:dog'
Is there a common recipe to accomplish that? I can't come up with any
solution...

Thanks in advance
Cesco
cokofreedom@gmail.com
Guest
 
Posts: n/a
#2: Jan 9 '08

re: alternating string replace


On Jan 9, 11:34 am, cesco <fd.calabr...@gmail.comwrote:
Quote:
Hi,
>
say I have a string like the following:
s1 = 'hi_cat_bye_dog'
and I want to replace the even '_' with ':' and the odd '_' with ','
so that I get a new string like the following:
s2 = 'hi:cat,bye:dog'
Is there a common recipe to accomplish that? I can't come up with any
solution...
>
Thanks in advance
Cesco
For replacing every other one, I tend to use the modulo, with a
counter.

count = (if u want even start with 0 else do 1)

while/for replacing /in lalastring:
if count % 2 == 0:
do even
else:
do odd
count += 1

This is a rather basic way of doing it, and I am sure people will sure
much more efficient ways, but it generally works for me.

Though I am now wondering if count % 2 when count == 2 is true or
false as it returns 0

Of course you still need to do your replace but you should be able to
do that.
Fredrik Lundh
Guest
 
Posts: n/a
#3: Jan 9 '08

re: alternating string replace


cesco wrote:
Quote:
and I want to replace the even '_' with ':' and the odd '_' with ','
so that I get a new string like the following:
s2 = 'hi:cat,bye:dog'
Is there a common recipe to accomplish that? I can't come up with any
solution...
how about splitting on "_", joining pairs with ":", and finally joining
the result with "," ?
Quote:
Quote:
Quote:
>>s1 = "hi_cat_bye_dog"
>>s1 = s1.split("_")
>>s1
['hi', 'cat', 'bye', 'dog']
Quote:
Quote:
Quote:
>>s1 = [s1[i]+":"+s1[i+1] for i in range(0,len(s1),2)]
>>s1
['hi:cat', 'bye:dog']
Quote:
Quote:
Quote:
>>s1 = ",".join(s1)
>>s1
'hi:cat,bye:dog'

(there are many other ways to do it, but the above 3-liner is short and
straightforward. note the use of range() to step over every other item
in the list)

</F>

Peter Otten
Guest
 
Posts: n/a
#4: Jan 9 '08

re: alternating string replace


cesco wrote:
Quote:
say I have a string like the following: s1 = 'hi_cat_bye_dog'
and I want to replace the even '_' with ':' and the odd '_' with ',' so
that I get a new string like the following: s2 = 'hi:cat,bye:dog'
Quote:
Quote:
Quote:
>>import re
>>from itertools import cycle
>>re.sub("_", lambda m, c=cycle(":,").next: c(), "hi_cat_bye_dog")
'hi:cat,bye:dog'
Quote:
Is there a common recipe to accomplish that? I can't come up with any
solution...
There are many. If you want to learn Python don't be afraid to write it
in a long-winded way (with loops and helper functions) first.

Peter
Duncan Booth
Guest
 
Posts: n/a
#5: Jan 9 '08

re: alternating string replace


cesco <fd.calabrese@gmail.comwrote:
Quote:
Hi,
>
say I have a string like the following:
s1 = 'hi_cat_bye_dog'
and I want to replace the even '_' with ':' and the odd '_' with ','
so that I get a new string like the following:
s2 = 'hi:cat,bye:dog'
Is there a common recipe to accomplish that? I can't come up with any
solution...
>
Here's yet another answer:

from itertools import islice, cycle

def interleave(*iterators):
iterators = [ iter(i) for i in iterators ]
while 1:
for i in iterators:
yield i.next()


def punctuate(s):
parts = s.split('_')
punctuation = islice(cycle(':,'), len(parts)-1)
return ''.join(interleave(parts, punctuation))

s1 = 'hi_cat_bye_dog'
print punctuate(s1)


# Or as a one-liner (once you have interleave):

print ''.join(list(interleave(s1.split('_'), cycle(':,')))[:-1])
bearophileHUGS@lycos.com
Guest
 
Posts: n/a
#6: Jan 9 '08

re: alternating string replace


My version, uses a re.sub, plus a function used as an object with a
one bit state:

from re import sub

def repl(o):
repl.n = not repl.n
return ":" if repl.n else ","
repl.n = False

print sub("_", repl, "hi_cat_bye_dog_foo_bar_red")

Bye,
bearophile
cokofreedom@gmail.com
Guest
 
Posts: n/a
#7: Jan 9 '08

re: alternating string replace


Designed a pretty basic way that is "acceptable" on small strings.

evenOrOdd = True
s1 = "hi_cat_bye_dog_foo_bar_red"
s2 = ""

for i in s1:
if i == '_':
if evenOrOdd:
s2 += ':'
evenOrOdd = not evenOrOdd
else:
s2 += ','
evenOrOdd = not evenOrOdd
else:
s2 += i

print s2
Neil Cerutti
Guest
 
Posts: n/a
#8: Jan 9 '08

re: alternating string replace


On Jan 9, 2008 5:34 AM, cesco <fd.calabrese@gmail.comwrote:
Quote:
Hi,
>
say I have a string like the following:
s1 = 'hi_cat_bye_dog'
and I want to replace the even '_' with ':' and the odd '_' with ','
so that I get a new string like the following:
s2 = 'hi:cat,bye:dog'
Is there a common recipe to accomplish that? I can't come up with any
solution...
>
Thanks in advance
Hum, hum... If I had a hammer...

from pyparsing import *

word = Word(alphas)
sep = Literal('_').suppress()
pair = Group(word + sep + word)
pairs = delimitedList(pair, '_')

print ','.join(':'.join(t) for t in
pairs.parseString('hi_cat_bye_dog').asList())

--
Neil Cerutti <mr.cerutti+python@gmail.com>
Neil Cerutti
Guest
 
Posts: n/a
#9: Jan 9 '08

re: alternating string replace


On Jan 9, 2008 5:34 AM, cesco <fd.calabrese@gmail.comwrote:
Quote:
Hi,
>
say I have a string like the following:
s1 = 'hi_cat_bye_dog'
and I want to replace the even '_' with ':' and the odd '_' with ','
so that I get a new string like the following:
s2 = 'hi:cat,bye:dog'
Is there a common recipe to accomplish that? I can't come up with any
solution...
>
Thanks in advance
Hum, hum... If I had a hammer...
from pyparsing import *

word = Word(alphas)
sep = Literal('_').suppress()
pair = Group(word + sep + word)
pairs = delimitedList(pair, '_')

print ','.join(':'.join(t) for t in
pairs.parseString('hi_cat_bye_dog').asList())

--
Neil Cerutti <mr.cerutti+python@gmail.com>
Pablo Ziliani
Guest
 
Posts: n/a
#10: Jan 9 '08

re: alternating string replace


cesco wrote:
Quote:
Hi,
>
say I have a string like the following:
s1 = 'hi_cat_bye_dog'
and I want to replace the even '_' with ':' and the odd '_' with ','
so that I get a new string like the following:
s2 = 'hi:cat,bye:dog'
Is there a common recipe to accomplish that? I can't come up with any
solution...
What about:
Quote:
Quote:
Quote:
>>import re
>>s1 = 'hi_cat_bye_dog'
>>print re.sub(r'([^_]+)_([^_]+)_?', r'\1:\2;', s1)
hi:cat;bye:dog;

it still works for a longer string:
Quote:
Quote:
Quote:
>>s1 = 'hi_cat_bye_dog_' + s1
>>s1
'hi_cat_bye_dog_hi_cat_bye_dog'
Quote:
Quote:
Quote:
>>print re.sub(r'([^_]+)_([^_]+)_?', r'\1:\2;', s1)
hi:cat;bye:dog;hi:cat;bye:dog;


Donald 'Paddy' McCarthy
Guest
 
Posts: n/a
#11: Jan 9 '08

re: alternating string replace


cesco wrote:
I created some more test strings and ran posters solutions against them.

results attached.

- Paddy.






# alternating_replacements.py

tests = " 1 2_ 3_4 5_6_ 7_8_9 10_11_12_ 13_14_15_16 17_18_19_20_" \
" _ _21 _22_ _23_24 _25_26_ _27_28_29 _30_31_32_ _33_34_35_36" \
" __ ___ ____ _____".split(" ")

def altrep0(s):
s1 = s.split("_")
s1 = [s1[i]+":"+s1[i+1] for i in range(0,len(s1),2)]
s1 = ",".join(s1)
return s1
altrep0.author="Frederik Lundh"

def altrep1(s):
from re import sub
def repl(o):
repl.n = not repl.n
return ":" if repl.n else ","
repl.n = False
return sub("_", repl, s)
altrep1.author="bearophile"

def altrep2(s):
evenOrOdd = True
s2 = ""
for i in s:
if i == '_':
if evenOrOdd:
s2 += ':'
evenOrOdd = not evenOrOdd
else:
s2 += ','
evenOrOdd = not evenOrOdd
else:
s2 += i
return s2
altrep2.author="cokofree"

def altrep3(s):
import re
from itertools import cycle
return re.sub("_", lambda m, c=cycle(":,").next: c(), s)
altrep3.author="Peter Otten"

def altrep4(s):
from itertools import islice, cycle
def interleave(*iterators):
iterators = [ iter(i) for i in iterators ]
while 1:
for i in iterators:
yield i.next()
def punctuate(s):
parts = s.split('_')
punctuation = islice(cycle(':,'), len(parts)-1)
return ''.join(interleave(parts, punctuation))

return punctuate(s)
altrep4.author="Duncan Booth"

def altrep5(s):
import re
return re.sub(r'([^_]+)_([^_]+)_?', r'\1:\2;', s)
altrep5.author="Pablo Ziliani"

progs = [ altrep0, altrep1, altrep2, altrep3, altrep4, altrep5]

def testall():
'''
Quote:
Quote:
Quote:
>>testall()
## Program by: Frederik Lundh
'' RETURNS '<type 'exceptions.IndexError'>'
'1' RETURNS '<type 'exceptions.IndexError'>'
'2_' RETURNS '2:'
'3_4' RETURNS '3:4'
'5_6_' RETURNS '<type 'exceptions.IndexError'>'
'7_8_9' RETURNS '<type 'exceptions.IndexError'>'
'10_11_12_' RETURNS '10:11,12:'
'13_14_15_16' RETURNS '13:14,15:16'
'17_18_19_20_' RETURNS '<type 'exceptions.IndexError'>'
'_' RETURNS ':'
'_21' RETURNS ':21'
'_22_' RETURNS '<type 'exceptions.IndexError'>'
'_23_24' RETURNS '<type 'exceptions.IndexError'>'
'_25_26_' RETURNS ':25,26:'
'_27_28_29' RETURNS ':27,28:29'
'_30_31_32_' RETURNS '<type 'exceptions.IndexError'>'
'_33_34_35_36' RETURNS '<type 'exceptions.IndexError'>'
'__' RETURNS '<type 'exceptions.IndexError'>'
'___' RETURNS ':,:'
'____' RETURNS '<type 'exceptions.IndexError'>'
'_____' RETURNS ':,:,:'

## Program by: bearophile
'' RETURNS ''
'1' RETURNS '1'
'2_' RETURNS '2:'
'3_4' RETURNS '3:4'
'5_6_' RETURNS '5:6,'
'7_8_9' RETURNS '7:8,9'
'10_11_12_' RETURNS '10:11,12:'
'13_14_15_16' RETURNS '13:14,15:16'
'17_18_19_20_' RETURNS '17:18,19:20,'
'_' RETURNS ':'
'_21' RETURNS ':21'
'_22_' RETURNS ':22,'
'_23_24' RETURNS ':23,24'
'_25_26_' RETURNS ':25,26:'
'_27_28_29' RETURNS ':27,28:29'
'_30_31_32_' RETURNS ':30,31:32,'
'_33_34_35_36' RETURNS ':33,34:35,36'
'__' RETURNS ':,'
'___' RETURNS ':,:'
'____' RETURNS ':,:,'
'_____' RETURNS ':,:,:'

## Program by: cokofree
'' RETURNS ''
'1' RETURNS '1'
'2_' RETURNS '2:'
'3_4' RETURNS '3:4'
'5_6_' RETURNS '5:6,'
'7_8_9' RETURNS '7:8,9'
'10_11_12_' RETURNS '10:11,12:'
'13_14_15_16' RETURNS '13:14,15:16'
'17_18_19_20_' RETURNS '17:18,19:20,'
'_' RETURNS ':'
'_21' RETURNS ':21'
'_22_' RETURNS ':22,'
'_23_24' RETURNS ':23,24'
'_25_26_' RETURNS ':25,26:'
'_27_28_29' RETURNS ':27,28:29'
'_30_31_32_' RETURNS ':30,31:32,'
'_33_34_35_36' RETURNS ':33,34:35,36'
'__' RETURNS ':,'
'___' RETURNS ':,:'
'____' RETURNS ':,:,'
'_____' RETURNS ':,:,:'

## Program by: Peter Otten
'' RETURNS ''
'1' RETURNS '1'
'2_' RETURNS '2:'
'3_4' RETURNS '3:4'
'5_6_' RETURNS '5:6,'
'7_8_9' RETURNS '7:8,9'
'10_11_12_' RETURNS '10:11,12:'
'13_14_15_16' RETURNS '13:14,15:16'
'17_18_19_20_' RETURNS '17:18,19:20,'
'_' RETURNS ':'
'_21' RETURNS ':21'
'_22_' RETURNS ':22,'
'_23_24' RETURNS ':23,24'
'_25_26_' RETURNS ':25,26:'
'_27_28_29' RETURNS ':27,28:29'
'_30_31_32_' RETURNS ':30,31:32,'
'_33_34_35_36' RETURNS ':33,34:35,36'
'__' RETURNS ':,'
'___' RETURNS ':,:'
'____' RETURNS ':,:,'
'_____' RETURNS ':,:,:'

## Program by: Duncan Booth
'' RETURNS ''
'1' RETURNS '1'
'2_' RETURNS '2:'
'3_4' RETURNS '3:4'
'5_6_' RETURNS '5:6,'
'7_8_9' RETURNS '7:8,9'
'10_11_12_' RETURNS '10:11,12:'
'13_14_15_16' RETURNS '13:14,15:16'
'17_18_19_20_' RETURNS '17:18,19:20,'
'_' RETURNS ':'
'_21' RETURNS ':21'
'_22_' RETURNS ':22,'
'_23_24' RETURNS ':23,24'
'_25_26_' RETURNS ':25,26:'
'_27_28_29' RETURNS ':27,28:29'
'_30_31_32_' RETURNS ':30,31:32,'
'_33_34_35_36' RETURNS ':33,34:35,36'
'__' RETURNS ':,'
'___' RETURNS ':,:'
'____' RETURNS ':,:,'
'_____' RETURNS ':,:,:'

## Program by: Pablo Ziliani
'' RETURNS ''
'1' RETURNS '1'
'2_' RETURNS '2_'
'3_4' RETURNS '3:4;'
'5_6_' RETURNS '5:6;'
'7_8_9' RETURNS '7:8;9'
'10_11_12_' RETURNS '10:11;12_'
'13_14_15_16' RETURNS '13:14;15:16;'
'17_18_19_20_' RETURNS '17:18;19:20;'
'_' RETURNS '_'
'_21' RETURNS '_21'
'_22_' RETURNS '_22_'
'_23_24' RETURNS '_23:24;'
'_25_26_' RETURNS '_25:26;'
'_27_28_29' RETURNS '_27:28;29'
'_30_31_32_' RETURNS '_30:31;32_'
'_33_34_35_36' RETURNS '_33:34;35:36;'
'__' RETURNS '__'
'___' RETURNS '___'
'____' RETURNS '____'
'_____' RETURNS '_____'
Quote:
Quote:
Quote:
>>>
'''
import sys
for prog in progs:
print "\n## Program by:", prog.author
for test in tests:
try:
answer = prog(test)
except:
answer = sys.exc_info()[0]
print "%14s RETURNS '%s'" % ("'%s'" % (test,), answer)

if __name__ == "__main__":
testall()

Paul McGuire
Guest
 
Posts: n/a
#12: Jan 9 '08

re: alternating string replace


On Jan 9, 7:41*am, "Neil Cerutti" <mr.ceru...@gmail.comwrote:
Quote:
On Jan 9, 2008 5:34 AM, cesco <fd.calabr...@gmail.comwrote:
>
Quote:
Hi,
>
Quote:
say I have a string like the following:
s1 = 'hi_cat_bye_dog'
and I want to replace the even '_' with ':' and the odd '_' with ','
so that I get a new string like the following:
s2 = 'hi:cat,bye:dog'
Is there a common recipe to accomplish that? I can't come up with any
solution...
>
Quote:
Thanks in advance
>
Hum, hum... If I had a hammer...
>
frompyparsingimport *
>
word = Word(alphas)
sep = Literal('_').suppress()
pair = Group(word + sep + word)
pairs = delimitedList(pair, '_')
>
print ','.join(':'.join(t) for t in
* * * * * * * *pairs.parseString('hi_cat_bye_dog').asList())
>
--
Neil Cerutti <mr.cerutti+pyt...@gmail.com>
My suspicious nature sees the following coming along...

d1 = eval("{"+s2+"}")

You can have pyparsing create the tuples for you, and then convert to
a dict at the end with a constructor - no eval needed.

from pyparsing import *

word = Word(alphas)
sep = Literal('_').suppress()
pair = Group(word + sep + word).setParseAction(lambda toks:
tuple(*toks))
pairs = delimitedList(pair, '_')

print dict(pairs.parseString('hi_cat_bye_dog').asList())

Prints:

{'bye': 'dog', 'hi': 'cat'}

-- Paul
bearophileHUGS@lycos.com
Guest
 
Posts: n/a
#13: Jan 9 '08

re: alternating string replace


Donald 'Paddy' McCarthy:

[... lots and lots and lots of tests...]

C'mon Paddy, where are the timings too? Are you becoming lazy
lately? ;-)

Bear bugs,
bearophile
Fredrik Lundh
Guest
 
Posts: n/a
#14: Jan 9 '08

re: alternating string replace


Donald 'Paddy' McCarthy wrote:
Quote:
I created some more test strings and ran posters solutions against them.
the point being?

</F>

Paddy
Guest
 
Posts: n/a
#15: Jan 9 '08

re: alternating string replace


On Jan 9, 8:47 pm, bearophileH...@lycos.com wrote:
Quote:
Donald 'Paddy' McCarthy:
>
[... lots and lots and lots of tests...]
>
C'mon Paddy, where are the timings too? Are you becoming lazy
lately? ;-)
>
Bear bugs,
bearophile
Get it right before you get it fast. But what is 'right'.
Paddy
Guest
 
Posts: n/a
#16: Jan 9 '08

re: alternating string replace


On Jan 9, 8:56 pm, Fredrik Lundh <fred...@pythonware.comwrote:
Quote:
Donald 'Paddy' McCarthy wrote:
Quote:
I created some more test strings and ran posters solutions against them.
>
the point being?
>
</F>
To see how they act against 'corner cases' and
an exercise for me in trying to create corner cases. (I'm in to
functional testing at the mo').

- Paddy.
Fredrik Lundh
Guest
 
Posts: n/a
#17: Jan 9 '08

re: alternating string replace


Paddy wrote:
Quote:
To see how they act against 'corner cases' and
an exercise for me in trying to create corner cases. (I'm in to
functional testing at the mo').
sounds more like "pulling requirements out of thin air". not sure that
helps the OP get a better understanding of Python, really.

</F>

Paddy
Guest
 
Posts: n/a
#18: Jan 9 '08

re: alternating string replace


On Jan 9, 9:29 pm, Paddy <paddy3...@googlemail.comwrote:
Quote:
On Jan 9, 8:56 pm, Fredrik Lundh <fred...@pythonware.comwrote:
>
Quote:
Donald 'Paddy' McCarthy wrote:
Quote:
I created some more test strings and ran posters solutions against them.
>
Quote:
the point being?
>
Quote:
</F>
>
To see how they act against 'corner cases' and
an exercise for me in trying to create corner cases. (I'm in to
functional testing at the mo').
>
- Paddy.
.... Then there is seeing how multiple interpretations of a real world
(i.e. limited), spec. act on an extended dataset. The limited spec
comes up all the time in the design and verification of digital
circuits. Then again, I was also waiting on someone and it passed the
time amiably :-)

- Paddy.
Paddy
Guest
 
Posts: n/a
#19: Jan 9 '08

re: alternating string replace


On Jan 9, 9:39 pm, Fredrik Lundh <fred...@pythonware.comwrote:
Quote:
Paddy wrote:
Quote:
To see how they act against 'corner cases' and
an exercise for me in trying to create corner cases. (I'm in to
functional testing at the mo').
>
sounds more like "pulling requirements out of thin air". not sure that
helps the OP get a better understanding of Python, really.
>
</F>
Not really out of thin air. The OP transforming alternating
occurrences of _ so corners would include a null string; strings with
1, 2 and 3 occurrences of the character to be replaced and the char to
be replaced separated or not by other chars....

Ideally I would create a randomized interesting string generator and
try each prog against a lot of generated examples and computed
'correct' answers, but I am unsure of what should be the right answer
in some cases so the earlier posting can be used to give extra
information for the spec. to be fleshed out with.

You may be right in that the OP might see the extended input and
dismiss them because he knows that the input data is never going to be
like that - or - he may find that his input validation might well
allow some of the cases through and he needs to either improve his
input validation or define what to do with more types of input.

Your also right in that its mostly not Python specific but it helps me
think of corner cases and the interpretation of specs which is very
important in helping solve the right problem.

- Paddy.

Gordon C
Guest
 
Posts: n/a
#20: Jan 10 '08

re: alternating string replace


This is very cool stuff but I suspect that the code is unreadable to many
readers, including me. Just for fun here is a complete program, written in
Turbo Pascal, circa 1982, that does the job. Readable n'est pas?

Program dash;
var str: string[80];
n: integer;
odd: boolean;
begin
str:='Hi there_how are you?_';
odd::=TRUE;
for n:= 1 to length(str) do begin
if ((str[n]='_') and (odd=TRUE)) then begin
str[n]:= ',';
odd:=FALSE; end
else
if ((str[n]='_') and (odd=FALSE) then begin
str[n]:= ':';
odd:= TRUE; end;
end; {for}
writeln(str);
end. {dash}

Regards,
Gord


bearophileHUGS@lycos.com
Guest
 
Posts: n/a
#21: Jan 10 '08

re: alternating string replace


Gordon C:
Quote:
This is very cool stuff but I suspect that the code is unreadable
to many readers, including me. Just for fun here is a complete program,
written in Turbo Pascal, circa 1982, that does the job. Readable
n'est pas?
I think it's quite readable, especially if you indent it more
correctly.
Pascal is usually among the most readable languages, for not-too-much
complex tasks. I don't mind its mutable strings too much.

Bye,
bearophile
cokofreedom@gmail.com
Guest
 
Posts: n/a
#22: Jan 10 '08

re: alternating string replace


On Jan 10, 3:46 am, bearophileH...@lycos.com wrote:
Quote:
Gordon C:
>
Quote:
This is very cool stuff but I suspect that the code is unreadable
to many readers, including me. Just for fun here is a complete program,
written in Turbo Pascal, circa 1982, that does the job. Readable
n'est pas?
>
I think it's quite readable, especially if you indent it more
correctly.
Pascal is usually among the most readable languages, for not-too-much
complex tasks. I don't mind its mutable strings too much.
>
Bye,
bearophile
And for me to feel a tiny bit happier, is very similar to mine :)
cokofreedom@gmail.com
Guest
 
Posts: n/a
#23: Jan 11 '08

re: alternating string replace


evenOrOdd = True
s1, s2 = "hi_cat_bye_dog_foo_bar_red", ""

for i in s1:
if i == '_':
s2 += ':' if evenOrOdd else ','
evenOrOdd = not evenOrOdd
else:
s2 += i

print s2

Presently I cannot work out how to use .join instead of += ...
While I realise this is producing a new string (and I believe +=
rebuilds it a lot?) how much slower
is this going to be over the others?
Chris
Guest
 
Posts: n/a
#24: Jan 11 '08

re: alternating string replace


On Jan 9, 12:34 pm, cesco <fd.calabr...@gmail.comwrote:
Quote:
Hi,
>
say I have a string like the following:
s1 = 'hi_cat_bye_dog'
and I want to replace the even '_' with ':' and the odd '_' with ','
so that I get a new string like the following:
s2 = 'hi:cat,bye:dog'
Is there a common recipe to accomplish that? I can't come up with any
solution...
>
Thanks in advance
Cesco
A simple list comprehension is all that is needed.

input_string = 'hi_cat_bye_dog'.split('_')
output_string = ','.join([':'.join(input_string[i:i+2]) for i in
xrange(0,len(input_string),2)])
bearophileHUGS@lycos.com
Guest
 
Posts: n/a
#25: Jan 11 '08

re: alternating string replace


Dennis Lee Bieber:
Quote:
So� in Python, your str[n] :=
':' just can not be done! You would have to create a new string
containing everything in front of n, the ':', and then everything behind
n (skipping n itself, of course). This is a painfully slow operation in
Python as it allocates memory for the parts, allocates memory for the
new combined string, and then garbage collects (potentially) the
original string and parts. The recommended Python idiom is to break
strings into a list of separate parts (str.split('_'), for example),
manipulate those parts, and at the end of manipulation, rejoin them
using some delimiter ( ",".join(partslist) )
An alternative solution, that's often good, expecially wity Psyco, is
to use an:
array.array("c", originalstring)
and then mutate it, as you do with Pascal strings.

Bye,
bearophile
Paddy
Guest
 
Posts: n/a
#26: Jan 11 '08

re: alternating string replace


On Jan 11, 9:31 am, cokofree...@gmail.com wrote:
Quote:
evenOrOdd = True
s1, s2 = "hi_cat_bye_dog_foo_bar_red", ""
>
for i in s1:
if i == '_':
s2 += ':' if evenOrOdd else ','
evenOrOdd = not evenOrOdd
else:
s2 += i
>
print s2
>
Presently I cannot work out how to use .join instead of += ...
Do
s2 = []
then later: s2.append(i)

and at the end: print ''.join(s2)


- Paddy.
Quote:
While I realise this is producing a new string (and I believe +=
rebuilds it a lot?) how much slower
is this going to be over the others?
Paddy
Guest
 
Posts: n/a
#27: Jan 11 '08

re: alternating string replace


On Jan 11, 9:54 am, Chris <cwi...@gmail.comwrote:
Quote:
On Jan 9, 12:34 pm, cesco <fd.calabr...@gmail.comwrote:
>
Quote:
Hi,
>
Quote:
say I have a string like the following:
s1 = 'hi_cat_bye_dog'
and I want to replace the even '_' with ':' and the odd '_' with ','
so that I get a new string like the following:
s2 = 'hi:cat,bye:dog'
Is there a common recipe to accomplish that? I can't come up with any
solution...
>
Quote:
Thanks in advance
Cesco
>
A simple list comprehension is all that is needed.
>
input_string = 'hi_cat_bye_dog'.split('_')
output_string = ','.join([':'.join(input_string[i:i+2]) for i in
xrange(0,len(input_string),2)])
I tried your example with my extended input cases to get:


def altrep6(s):
input_string = s.split('_')
return ','.join([':'.join(input_string[i:i+2])
for i in xrange(0,len(input_string),2)])
altrep6.author="Chris"


Giving output:


## Program by: Chris
'' RETURNS ''
'1' RETURNS '1'
'2_' RETURNS '2:'
'3_4' RETURNS '3:4'
'5_6_' RETURNS '5:6,'
'7_8_9' RETURNS '7:8,9'
'10_11_12_' RETURNS '10:11,12:'
'13_14_15_16' RETURNS '13:14,15:16'
'17_18_19_20_' RETURNS '17:18,19:20,'
'_' RETURNS ':'
'_21' RETURNS ':21'
'_22_' RETURNS ':22,'
'_23_24' RETURNS ':23,24'
'_25_26_' RETURNS ':25,26:'
'_27_28_29' RETURNS ':27,28:29'
'_30_31_32_' RETURNS ':30,31:32,'
'_33_34_35_36' RETURNS ':33,34:35,36'
'__' RETURNS ':,'
'___' RETURNS ':,:'
'____' RETURNS ':,:,'
'_____' RETURNS ':,:,:'


- Paddy.


Reedick, Andrew
Guest
 
Posts: n/a
#28: Jan 11 '08

re: alternating string replace


-----Original Message-----
Quote:
From: python-list-bounces+jr9445=att.com@python.org [mailto:python-
list-bounces+jr9445=att.com@python.org] On Behalf Of cesco
Sent: Wednesday, January 09, 2008 5:34 AM
To: python-list@python.org
Subject: alternating string replace

Hi,

say I have a string like the following:
s1 = 'hi_cat_bye_dog'
and I want to replace the even '_' with ':' and the odd '_' with ','
so that I get a new string like the following:
s2 = 'hi:cat,bye:dog'
Is there a common recipe to accomplish that? I can't come up with any
solution...

For those of us who still think in Perl, here's an easy to read, lazy
solution:

s = 'hi_cat_bye_dog'
print s
s = re.sub(r'_(.*?(_|$))', r':\1', s) ## every odd '_' to ':'
print s
s = re.sub(r'_', r',', s) ## every even '_' to ','
print s
Quote:
hi_cat_bye_dog
hi:cat_bye:dog
hi:cat,bye:dog

The equivalent Perl code:
my $s = 'hi_cat_bye_dog';

print $s, "\n";
$s =~ s/_(.*?(_|$))/:$1/g;
print $s, "\n";
$s =~ s/_/,/g;
print $s, "\n";


George Sakkis
Guest
 
Posts: n/a
#29: Jan 12 '08

re: alternating string replace


On Jan 9, 6:34 am, Duncan Booth <duncan.bo...@invalid.invalidwrote:
Quote:
cesco <fd.calabr...@gmail.comwrote:
Quote:
Hi,
>
Quote:
say I have a string like the following:
s1 = 'hi_cat_bye_dog'
and I want to replace the even '_' with ':' and the odd '_' with ','
so that I get a new string like the following:
s2 = 'hi:cat,bye:dog'
Is there a common recipe to accomplish that? I can't come up with any
solution...
>
Here's yet another answer:
>
from itertools import islice, cycle
>
def interleave(*iterators):
iterators = [ iter(i) for i in iterators ]
while 1:
for i in iterators:
yield i.next()
>
def punctuate(s):
parts = s.split('_')
punctuation = islice(cycle(':,'), len(parts)-1)
return ''.join(interleave(parts, punctuation))
>
s1 = 'hi_cat_bye_dog'
print punctuate(s1)
>
# Or as a one-liner (once you have interleave):
>
print ''.join(list(interleave(s1.split('_'), cycle(':,')))[:-1])
And yet another itertools-addicted one-liner (leaving out the import):

from itertools import chain, izip, cycle
print ''.join(chain(*izip(s1.split('_'),cycle(':,'))))[:-1]

George
Paul Rubin
Guest
 
Posts: n/a
#30: Jan 12 '08

re: alternating string replace


George Sakkis <george.sakkis@gmail.comwrites:
Quote:
from itertools import chain, izip, cycle
print ''.join(chain(*izip(s1.split('_'),cycle(':,'))))[:-1]
from itertools import cycle
a = cycle(':,')
print re.sub('_', lambda x: a.next(), s1)
Steven D'Aprano
Guest
 
Posts: n/a
#31: Jan 12 '08

re: alternating string replace


On Fri, 11 Jan 2008 14:55:18 -0600, Reedick, Andrew wrote:
Quote:
For those of us who still think in Perl, here's an easy to read
....
Quote:
s = re.sub(r'_(.*?(_|$))', r':\1', s)
"Easy to read"? Oh that's priceless. Andrew, you should consider writing
comedy professionally!



--
Steven
Pablo Ziliani
Guest
 
Posts: n/a
#32: Jan 12 '08

re: alternating string replace


Paul Rubin wrote:
Quote:
George Sakkis <george.sakkis@gmail.comwrites:
>
Quote:
>from itertools import chain, izip, cycle
>print ''.join(chain(*izip(s1.split('_'),cycle(':,'))))[:-1]
>>
>
from itertools import cycle
a = cycle(':,')
print re.sub('_', lambda x: a.next(), s1)
>
Lovely.

If there OP didn't vanished into thin air*, I'd declare you the winner
(although you forgot to import re).
This said, I'm still kind of partial to any re-only solution, but it
would require someone outlines the behavior in the corner cases.

* die, thread!

--
Pablo
Paddy
Guest
 
Posts: n/a
#33: Jan 12 '08

re: alternating string replace


On Jan 12, 2:55 am, Pablo Ziliani <pa...@decode.com.arwrote:
Quote:
* die, thread!
:-)


def altrep7(s):
from itertools import cycle
import re
a = cycle(':,')
return re.sub('_', lambda x: a.next(), s)
altrep7.author="George Sakkis(&Paul Rubin)"

Gives:



## Program by: George Sakkis(&Paul Rubin)
'' RETURNS ''
'1' RETURNS '1'
'2_' RETURNS '2:'
'3_4' RETURNS '3:4'
'5_6_' RETURNS '5:6,'
'7_8_9' RETURNS '7:8,9'
'10_11_12_' RETURNS '10:11,12:'
'13_14_15_16' RETURNS '13:14,15:16'
'17_18_19_20_' RETURNS '17:18,19:20,'
'_' RETURNS ':'
'_21' RETURNS ':21'
'_22_' RETURNS ':22,'
'_23_24' RETURNS ':23,24'
'_25_26_' RETURNS ':25,26:'
'_27_28_29' RETURNS ':27,28:29'
'_30_31_32_' RETURNS ':30,31:32,'
'_33_34_35_36' RETURNS ':33,34:35,36'
'__' RETURNS ':,'
'___' RETURNS ':,:'
'____' RETURNS ':,:,'
'_____' RETURNS ':,:,:'

- Paddy.
Paddy
Guest
 
Posts: n/a
#34: Jan 12 '08

re: alternating string replace


On Jan 11, 8:55 pm, "Reedick, Andrew" <jr9...@ATT.COMwrote:
Quote:
Quote:
-----Original Message-----
From: python-list-bounces+jr9445=att....@python.org [mailto:python-
list-bounces+jr9445=att....@python.org] On Behalf Of cesco
Sent: Wednesday, January 09, 2008 5:34 AM
To: python-l...@python.org
Subject: alternating string replace
>
Quote:
Hi,
>
Quote:
say I have a string like the following:
s1 = 'hi_cat_bye_dog'
and I want to replace the even '_' with ':' and the odd '_' with ','
so that I get a new string like the following:
s2 = 'hi:cat,bye:dog'
Is there a common recipe to accomplish that? I can't come up with any
solution...
>
For those of us who still think in Perl, here's an easy to read, lazy
solution:
>
s = 'hi_cat_bye_dog'
print s
s = re.sub(r'_(.*?(_|$))', r':\1', s) ## every odd '_' to ':'
print s
s = re.sub(r'_', r',', s) ## every even '_' to ','
print s
>
Quote:
hi_cat_bye_dog
hi:cat_bye:dog
hi:cat,bye:dog
>
The equivalent Perl code:
my $s = 'hi_cat_bye_dog';
>
print $s, "\n";
$s =~ s/_(.*?(_|$))/:$1/g;
print $s, "\n";
$s =~ s/_/,/g;
print $s, "\n";
def altrep8(s):
import re
s = re.sub(r'_(.*?(_|$))', r':\1', s) ## every odd '_' to ':'
return re.sub(r'_', r',', s) ## every even '_' to ','
altrep8.author="Reedick, Andrew"

Gives:

## Program by: Reedick, Andrew
'' RETURNS ''
'1' RETURNS '1'
'2_' RETURNS '2:'
'3_4' RETURNS '3:4'
'5_6_' RETURNS '5:6,'
'7_8_9' RETURNS '7:8,9'
'10_11_12_' RETURNS '10:11,12:'
'13_14_15_16' RETURNS '13:14,15:16'
'17_18_19_20_' RETURNS '17:18,19:20,'
'_' RETURNS ':'
'_21' RETURNS ':21'
'_22_' RETURNS ':22,'
'_23_24' RETURNS ':23,24'
'_25_26_' RETURNS ':25,26:'
'_27_28_29' RETURNS ':27,28:29'
'_30_31_32_' RETURNS ':30,31:32,'
'_33_34_35_36' RETURNS ':33,34:35,36'
'__' RETURNS ':,'
'___' RETURNS ':,:'
'____' RETURNS ':,:,'
'_____' RETURNS ':,:,:'
Closed Thread