【问题标题】:One-liner python script to separate a string with comma for every 2 characters [duplicate]单行python脚本,每2个字符用逗号分隔一个字符串[重复]
【发布时间】:2016-06-30 00:56:30
【问题描述】:

我在 Perl 下面做了一个单行来分隔字符串,例如080041ba,每 2 个字符加逗号。 我想知道是否有任何 Python 单线,至少不跨越多行,以实现相同的目标?

$ perl -e 'print((join ",","080041ba"=~/../g),"\n")'
08,00,41,ba

【问题讨论】:

    标签: python


    【解决方案1】:
    $ python -c 'import re; print re.sub("(..)(?!$)", r"\1,", "080041ba")'
    08,00,41,ba
    

    【讨论】:

    • 谢谢,但你为什么用r"\1,"而不是"\1,"?有什么区别吗?
    • @Zii 是的,因为在raw string literals ` 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,"` 中,您将每两个字符替换为字符"\x01,",这不是您想要的。你可以看看link
    • @Zii 是的,因为在raw string literals 中, \ 被按原样而不是作为转义序列(除非它出现在否则会终止文字的引号之前)。然后,如果您尝试使用“\1”,则将每两个字符替换为字符“\x01”,这不是您想要的。你可以看看what-exactly-do-u-and-r-string-flags-do-in-python-and-what-are-raw-string-l
    【解决方案2】:

    Pythonic way to insert every 2 elements in a string

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

    要将字符串 s 声明为行的一部分,只需添加 s = "...";例如:

    s = "080041ba"; ','.join(a+b for a,b in zip(s[::2], s[1::2]))
    

    【讨论】:

    • 这是非常 Pythonic 的。谢谢。
    • 当然!我想我应该提到 s 应该被声明为一个字符串,你可以内联
    猜你喜欢
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 2013-07-27
    • 2022-11-27
    • 2019-01-23
    相关资源
    最近更新 更多