【问题标题】:Split string each Nth character and join it back with different separators每个第 N 个字符拆分字符串并使用不同的分隔符将其连接回来
【发布时间】:2020-05-29 13:06:09
【问题描述】:

我尝试在具有不同分隔符的句子中使用文本换行。这正是我想要得到的输出:

'here are third-party[SEPARATOR1]extensions like[SEPARATOR2]Scener that allow us[SEPARATOR3]to watch content.'

这是我第一次尝试.join()wrap(),不成功:

[In] : 
sentence = '''here are third-party extensions like Scener that allow us to watch content.'''

separator = '[SEPARATOR]'

text = separator.join(wrap(sentence, 20))

[Out] :
'here are third-party[SEPARATOR]extensions like[SEPARATOR]Scener that allow us[SEPARATOR]to watch content.'

然后,我在分隔符内尝试了一个 for 循环,但也没有成功......:

[In] : 
sentence = '''here are third-party extensions like Scener that allow us to watch content.'''

for i in range(1, 4):
    separator = '[SEPARATOR' + str(i) + ']'

text = separator.join(wrap(sentence, 20))

[Out] :
'here are third-party[SEPARATOR3]extensions like[SEPARATOR3]Scener that allow us[SEPARATOR3]to watch content.'

也许结合 .split().join() 函数可能是一种更好的方法来做我想做的事,但我找不到如何做。请问,您知道如何实现这一目标吗?

【问题讨论】:

    标签: python string delimiter word-wrap


    【解决方案1】:

    这里有一个你可以尝试的单行:

    text = ''.join([(f'[SEPARATOR{i}]' if i else '') + w
                    for i, w in enumerate(wrap(sentence, 20))])
    

    【讨论】:

    • 我要在这里感谢大家。这个答案解决了我的问题,但是对于没有数字分隔符的人,如果分隔符是 A、B、C 而不是数字怎么办?我想我们不能使用enumerate 对吧?再次感谢您。
    • 要回答我关于字符串分隔符的问题,请参阅@Gabip 的回答。
    【解决方案2】:

    Wrap 为您提供可迭代的文本。如果您可以使用分隔符创建可迭代对象,则可以使用 "".join(t for pair in zip(wrapped_chunks, separators) for t in pair) 加入它们

    您可以使用无限生成器创建分隔符:

    def inf_separators():
        index = 1
        while True:
            yield f"SEPARATOR{index}"
            index = index + 1
    

    这会给你一个太多的分隔符,所以你可能想删除它或特别附加wrapped_chunks 的最后一项。

    如果您想在几个不同的分隔符之间交替使用,可以使用itertools.cycle(["SEP1", "SEP2", "SEP3"]) 来生成重复循环的令牌。

    【讨论】:

      【解决方案3】:

      试试这个:

      from textwrap import wrap
      
      sentence = '''here are third-party extensions like Scener that allow us to watch content.'''
      
      new_sentence = ""
      parts = wrap(sentence, 20)
      for i, part in enumerate(parts):
          new_sentence += part
          # adding separator after each part except for the last one
          if i < len(parts) - 1:
              new_sentence += f"[SEPARATOR{i+1}]"
      print(new_sentence)
      
      # output: here are third-party[SEPARATOR1]extensions like[SEPARATOR2]Scener that allow us[SEPARATOR3]to watch content.
      
      

      【讨论】:

      • 我也应该接受你的回答,因为它不仅解决了我的问题,还解决了将分隔符作为字符串的人(如 SEPARATOR_A、SEPARATOR_B 等。非常感谢。
      猜你喜欢
      • 2012-03-17
      • 2022-01-18
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      相关资源
      最近更新 更多