473,499 Members | 1,893 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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...

Thanks in advance
Cesco
Jan 9 '08 #1
33 2770
On Jan 9, 11:34 am, cesco <fd.calabr...@gmail.comwrote:
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.
Jan 9 '08 #2
cesco wrote:
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 "," ?
>>s1 = "hi_cat_bye_dog"
s1 = s1.split("_")
s1
['hi', 'cat', 'bye', 'dog']
>>s1 = [s1[i]+":"+s1[i+1] for i in range(0,len(s1),2)]
s1
['hi:cat', 'bye:dog']
>>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>

Jan 9 '08 #3
cesco wrote:
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'
>>import re
from itertools import cycle
re.sub("_", lambda m, c=cycle(":,").next: c(), "hi_cat_bye_dog")
'hi:cat,bye:dog'
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
Jan 9 '08 #4
cesco <fd**********@gmail.comwrote:
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])
Jan 9 '08 #5
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
Jan 9 '08 #6
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
Jan 9 '08 #7
On Jan 9, 2008 5:34 AM, cesco <fd**********@gmail.comwrote:
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***************@gmail.com>
Jan 9 '08 #8
On Jan 9, 2008 5:34 AM, cesco <fd**********@gmail.comwrote:
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***************@gmail.com>
Jan 9 '08 #9
cesco wrote:
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:
>>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:
>>s1 = 'hi_cat_bye_dog_' + s1
s1
'hi_cat_bye_dog_hi_cat_bye_dog'
>>print re.sub(r'([^_]+)_([^_]+)_?', r'\1:\2;', s1)
hi:cat;bye:dog;hi:cat;bye:dog;
Jan 9 '08 #10
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():
'''
>>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 '_____'
>>>
'''
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()

Jan 9 '08 #11
On Jan 9, 7:41*am, "Neil Cerutti" <mr.ceru...@gmail.comwrote:
On Jan 9, 2008 5:34 AM, cesco <fd.calabr...@gmail.comwrote:
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...

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
Jan 9 '08 #12
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
Jan 9 '08 #13
Donald 'Paddy' McCarthy wrote:
I created some more test strings and ran posters solutions against them.
the point being?

</F>

Jan 9 '08 #14
On Jan 9, 8:47 pm, bearophileH...@lycos.com wrote:
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'.
Jan 9 '08 #15
On Jan 9, 8:56 pm, Fredrik Lundh <fred...@pythonware.comwrote:
Donald 'Paddy' McCarthy wrote:
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.
Jan 9 '08 #16
Paddy wrote:
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>

Jan 9 '08 #17
On Jan 9, 9:29 pm, Paddy <paddy3...@googlemail.comwrote:
On Jan 9, 8:56 pm, Fredrik Lundh <fred...@pythonware.comwrote:
Donald 'Paddy' McCarthy wrote:
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.
.... 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.
Jan 9 '08 #18
On Jan 9, 9:39 pm, Fredrik Lundh <fred...@pythonware.comwrote:
Paddy wrote:
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.

Jan 9 '08 #19
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
Jan 10 '08 #20
Gordon C:
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
Jan 10 '08 #21
On Jan 10, 3:46 am, bearophileH...@lycos.com wrote:
Gordon C:
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 :)
Jan 10 '08 #22
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?
Jan 11 '08 #23
On Jan 9, 12:34 pm, cesco <fd.calabr...@gmail.comwrote:
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)])
Jan 11 '08 #24
Dennis Lee Bieber:
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
Jan 11 '08 #25
On Jan 11, 9:31 am, cokofree...@gmail.com wrote:
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.
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?
Jan 11 '08 #26
On Jan 11, 9:54 am, Chris <cwi...@gmail.comwrote:
On Jan 9, 12:34 pm, cesco <fd.calabr...@gmail.comwrote:
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)])
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.
Jan 11 '08 #27
-----Original Message-----
From: py********************************@python.org [mailto:python-
li*************************@python.org] On Behalf Of cesco
Sent: Wednesday, January 09, 2008 5:34 AM
To: py*********@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
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";
Jan 11 '08 #28
On Jan 9, 6:34 am, Duncan Booth <duncan.bo...@invalid.invalidwrote:
cesco <fd.calabr...@gmail.comwrote:
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])
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
Jan 12 '08 #29
George Sakkis <ge***********@gmail.comwrites:
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)
Jan 12 '08 #30
On Fri, 11 Jan 2008 14:55:18 -0600, Reedick, Andrew wrote:
For those of us who still think in Perl, here's an easy to read
....
s = re.sub(r'_(.*?(_|$))', r':\1', s)
"Easy to read"? Oh that's priceless. Andrew, you should consider writing
comedy professionally!

--
Steven
Jan 12 '08 #31
Paul Rubin wrote:
George Sakkis <ge***********@gmail.comwrites:
>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
Jan 12 '08 #32
On Jan 12, 2:55 am, Pablo Ziliani <pa...@decode.com.arwrote:
* 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.
Jan 12 '08 #33
On Jan 11, 8:55 pm, "Reedick, Andrew" <jr9...@ATT.COMwrote:
-----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
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
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 ':,:,:'
Jan 12 '08 #34

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1723
by: bettyann | last post by:
i am using templates via HTML_Template_IT to create a table from the results of a mysql query. i wanted to change the background image of alternating rows in the table. i thought i could do this...
1
4660
by: Eirik Eldorsen | last post by:
I'm trying to set alternating bgcolor for a datalist with 2 columns. My problem is that its the alternating cell that get the bgcolor, not the row. Is it possible to set alternating color of rows?...
9
2675
by: Max Weebler | last post by:
Hi, I have a datagrid built that has an alternating item style that sets the backcolor and ForeColor of its rows. I have 4 template columns. One of them has a LinkButton embedded in it to...
3
3688
by: Daniel Manes | last post by:
My DataGridView is set up like this: * Main row background color = white * Alternating row background color = light gray I also have a read-only (non-editable) column I want to show up as solid...
4
5665
by: mike | last post by:
how can I change the font color for an alternating row where the column data is formatted as a link? setting a style in the stylesheet for a { color:white; }
2
1305
by: Flubleah | last post by:
Hi there, I'm trying to create a function to make alternating uppercase and lowercase letters of a string using loops. e.g: funny = FuNnY or judge = JuDge Dim a As String =...
0
7007
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7220
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6894
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7388
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5470
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4919
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4600
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
1
665
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
297
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.