1

I made below Perl one-liner to separate a string, e.g. 080041ba, with comma for every 2 characters . I am wondering is there any Python one-liner, at least not spanning many lines, to achieve the same goal?

$ perl -e 'print((join ",","080041ba"=~/../g),"\n")'
08,00,41,ba
ThisSuitIsBlackNot
  • 23,492
  • 9
  • 63
  • 110
Zii
  • 359
  • 4
  • 10

2 Answers2

2
$ python -c 'import re; print re.sub("(..)(?!$)", r"\1,", "080041ba")'
08,00,41,ba
  • Thanks, but why did you use `r"\1,"` rather than `"\1,"` ? Is there any difference? – Zii Jun 30 '16 at 06:15
  • @Zii yes because in `raw string literals` the `\` is taken just as is and not as a escape sequence (unless it comes right before a quote that would otherwise terminate the literal). Then if you try with `"\1,"` instead you would replace each two characters by the characters `"\x01,"` which is not what you want. You can take a look at [link](http://stackoverflow.com/questions/2081640/what-exactly-do-u-and-r-string-flags-do-in-python-and-what-are-raw-string-l) – Eduardo Cuesta Jun 30 '16 at 06:43
  • 1
    @Zii yes because in `raw string literals` the \ is taken just as is and not as a escape sequence (unless it comes right before a quote that would otherwise terminate the literal). Then if you try with "\1," instead you would replace each two characters by the characters "\x01," which is not what you want. You can take a look at [what-exactly-do-u-and-r-string-flags-do-in-python-and-what-are-raw-string-l](http://stackoverflow.com/questions/2081640/what-exactly-do-u-and-r-string-flags-do-in-python-and-what-are-raw-string-l) – Eduardo Cuesta Jun 30 '16 at 06:53
1

Pythonic way to insert every 2 elements in a string

','.join(a+b for a,b in zip(s[::2], s[1::2]))

To declare string s as part of the line, just add s = "..."; e.g.:

s = "080041ba"; ','.join(a+b for a,b in zip(s[::2], s[1::2]))
Community
  • 1
  • 1
Checkmate
  • 1,074
  • 9
  • 16