Comma quibbling: Difference between revisions

Content deleted Content added
Walterpachl (talk | contribs)
m moved PL/I
Line 204:
{ABC and DEF}
{ABC, DEF, G and H}</pre>
 
=={{header|Python}}==
===replace() whilst reversed===
replace(..) can only replace the first X occurrences not the last
hence the replace is done on the reverse of the intermediate string
then reversed back.
<lang python>>>> def strcat(sequence):
return '{%s}' % ', '.join(sequence)[::-1].replace(',', 'dna ', 1)[::-1]
 
>>> for seq in ([], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]):
print('Input: %-24r -> Output: %r' % (seq, strcat(seq)))
 
Input: [] -> Output: '{}'
Input: ['ABC'] -> Output: '{ABC}'
Input: ['ABC', 'DEF'] -> Output: '{ABC and DEF}'
Input: ['ABC', 'DEF', 'G', 'H'] -> Output: '{ABC, DEF, G and H}'
>>> </lang>
 
===Counted replacement===
(Possible){{trans|Tcl}}
replace() will replace nothing if the count of items to replace is zero, (and negative integer counts act to replace all occurrences).
This combines with the length of the input sequence to allow this to work:
<lang python>def commaQuibble(s):
return '{%s}' % ' and '.join(s).replace(' and ', ', ', len(s) - 2)
 
for seq in ([], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]):
print('Input: %-24r -> Output: %r' % (seq, commaQuibble(seq)))</lang>
 
{{out}}
<pre>Input: [] -> Output: '{}'
Input: ['ABC'] -> Output: '{ABC}'
Input: ['ABC', 'DEF'] -> Output: '{ABC and DEF}'
Input: ['ABC', 'DEF', 'G', 'H'] -> Output: '{ABC, DEF, G and H}'</pre>
 
=={{header|PL/I}}==
Line 286 ⟶ 252:
{ABC, DEF, G, H}
</pre>
 
=={{header|Python}}==
===replace() whilst reversed===
replace(..) can only replace the first X occurrences not the last
hence the replace is done on the reverse of the intermediate string
then reversed back.
<lang python>>>> def strcat(sequence):
return '{%s}' % ', '.join(sequence)[::-1].replace(',', 'dna ', 1)[::-1]
 
>>> for seq in ([], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]):
print('Input: %-24r -> Output: %r' % (seq, strcat(seq)))
 
Input: [] -> Output: '{}'
Input: ['ABC'] -> Output: '{ABC}'
Input: ['ABC', 'DEF'] -> Output: '{ABC and DEF}'
Input: ['ABC', 'DEF', 'G', 'H'] -> Output: '{ABC, DEF, G and H}'
>>> </lang>
 
===Counted replacement===
(Possible){{trans|Tcl}}
replace() will replace nothing if the count of items to replace is zero, (and negative integer counts act to replace all occurrences).
This combines with the length of the input sequence to allow this to work:
<lang python>def commaQuibble(s):
return '{%s}' % ' and '.join(s).replace(' and ', ', ', len(s) - 2)
 
for seq in ([], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]):
print('Input: %-24r -> Output: %r' % (seq, commaQuibble(seq)))</lang>
 
{{out}}
<pre>Input: [] -> Output: '{}'
Input: ['ABC'] -> Output: '{ABC}'
Input: ['ABC', 'DEF'] -> Output: '{ABC and DEF}'
Input: ['ABC', 'DEF', 'G', 'H'] -> Output: '{ABC, DEF, G and H}'</pre>
 
=={{header|REXX}}==