代码之家  ›  专栏  ›  技术社区  ›  xRobot

如何用这种方式打印字符串

  •  4
  • xRobot  · 技术社区  · 15 年前

    例如:

    example_string = "this is an example string. ok ????"
    
    myfunction(example_string)
    
    "this i#s an e#xample# strin#g. ok #????"
    

    3 回复  |  直到 15 年前
        1
  •  9
  •   ʇsәɹoɈ    15 年前

    这个怎么样?

    '#'.join( [example_string[a:a+6] for a in range(0,len(example_string),6)])
    

    它也跑得很快。在我的机器上,每100个字符串5微秒:

    >>> import timeit
    >>> timeit.Timer( "'#'.join([s[a:a+6] for a in range(0,len(s),6)])", "s='x'*100").timeit()
    4.9556539058685303
    
        2
  •  4
  •   Amarghosh    15 年前
    >>> str = "this is an example string. ok ????"
    >>> import re
    >>> re.sub("(.{6})", r"\1#", str)
    'this i#s an e#xample# strin#g. ok #????'
    

    更新:
    通常点匹配除新行以外的所有字符。使用 re.S

    >>> pattern = re.compile("(.{6})", re.S)
    >>> str = "this is an example string with\nmore than one line\nin it. It has three lines"
    >>> print pattern.sub(r"\1#", str)
    

    this i#s an e#xample# strin#g with#
    more #than o#ne lin#e
    in i#t. It #has th#ree li#nes

        3
  •  2
  •   Ignacio Vazquez-Abrams    15 年前
    import itertools
    
    def every6(sin, c='#'):
      r = itertools.izip_longest(*([iter(sin)] * 6 + [c * (len(sin) // 6)]))
      return ''.join(''.join(y for y in x if y is not None) for x in r)
    
    print every6(example_string)