【问题标题】:Add line break after every 20 characters and save result as a new string [duplicate]每 20 个字符后添加换行符并将结果另存为新字符串 [重复]
【发布时间】:2020-12-02 03:59:50
【问题描述】:

我有一个字符串变量input = "A very very long string from user input",如何循环字符串并在 20 个字符后添加换行符\n,然后将格式化字符串保存在变量new_input 中?

到目前为止,我只能获取前 20 个字符,例如 input[0:20],但是您如何在整个字符串中执行此操作并在该点添加换行符?

【问题讨论】:

  • 你试过什么代码?你目前得到的输出有什么问题?

标签: python


【解决方案1】:

除了list comprehension + join 方法(顺便说一句很方便),您还可以使用python内置regex

import re
'\n'.join(re.findall('.{1,20}', string))

使其对每个nth 字符通用:

n = 20
'\n'.join(re.findall('.{1,%i}' % n, string))

正如@CrazyChuck 正确假设的那样,这可能比列表理解方法需要更长的时间。例如,给定一个包含 10 亿个字符的字符串(例如 string = 'A' * 10**9),使用 list comprehension 需要 10.6 秒,使用 regex 方法需要 12.6 秒。也许更大的字符串会有很大的不同,但没有那么大的字符串不是问题。

【讨论】:

  • 伙计...我知道这可能需要更长的时间才能运行(现在有点想测试它),但它非常简洁明了!非常易读的意图。唯一的问题是它省略了最后剩下的任何剩余字符。你知道是否有办法通过这种方法获得最后一点?
  • @CrazyChucky,你是对的!我已经更新了答案,我认为它现在可以正常工作了。
  • 不错!我以前从未真正使用过这样的重复范围。我很少看到关于 SO 的答案成为我最喜欢的新习语,因为它是如此基本的东西。这非常易读,以至于下次我需要拆分字符串时,除非我正在优化瓶颈,否则我认为这是要走的路。
【解决方案2】:

你可能想做这样的事情

inp = "A very very long string from user input"
new_input = ""
for i, letter in enumerate(inp):
    if i % 20 == 0:
        new_input += '\n'
    new_input += letter

# this is just because at the beginning too a `\n` character gets added
new_input = new_input[1:] 

【讨论】:

    【解决方案3】:

    假设您需要为每个第 n 个字符拆分一个字符串。

    那么你可以使用list comprehension。 这将为您提供字符串列表,您可以简单地使用join method 加入它。 像这样:

    some_str: str = "A very very long string from user input"
    n: int = 20
    splitted_str: List[str] = [some_str[i:i+n] for i in range(0, len(some_str), n)]
    result: str = "\n".join(splitted_str)
    

    【讨论】:

    • 如果您使用的是'\n'.join(),您可能还想在最后添加一个'\n'
    • 在问题中,有这个条件“在 20 个字符后添加换行符 \n”。为了完全正式,我们需要检查最后一个拆分字符串是否有 20 个字符,然后才添加一个\n。无论如何,尚不清楚我们是否需要它。
    • 好点,这是真的。不过,鼓励用换行符结束所有行可能是个好主意。
    • 赞成你的两种方法!在任何情况下,只需添加 + '\n' 就可以在这里工作(如果是这样的话。干得好!
    【解决方案4】:

    您可以访问正确长度的切片,而不是单独遍历每个字符。

    text = "A very very long string from user input"
    
    line_length = 5
    lines = []
    for i in range(0, len(text), line_length):
        lines.append(text[i:i+line_length] + '\n')
    print(''.join(lines))
    

    您可以用列表推导替换 for 循环:

    text = "A very very long string from user input"
    
    line_length = 5
    lines = [text[i:i+line_length] + '\n' for i in range(0, len(text), line_length)]
    print(''.join(lines))
    

    打印:

    A ver
    y ver
    y lon
    g str
    ing f
    rom u
    ser i
    nput
    

    line_length 更改为 20 以获得实际更长的输入。

    注意:如果最后一行少于 20 个字符,则按字面理解您的问题会省略最后的换行符 ('\n')。如果您愿意,您可以这样做,但是如果您要将其打印到屏幕上或保存到文件中,您可能希望最后一行有一个换行符,即使它是一个较短的剩余部分。

    【讨论】:

      【解决方案5】:

      这是为每 20 个字符添加一个新行的基本且详细的方法。

      user_input = "A very very long string from user input" #1
      char_count = 0 #2
      new_input_list = [] #3
      user_new_input = '' #4
      for c in user_input: #5 
              char_count += 1 #6 
              new_input_list.append(c) #7 
              if char_count == 20: #8 
                  new_input_list.append('\n') #9 
                  char_count = 0 #10 
      print(user_new_input.join(new_input_list)) #11 
      
      #1 user_input can't use input because that is a reserved word in python 
      #2 used to keep track of number of chars looped through
      #3 list to append the chars looped through and the '\n' (new line)
      #4 used to hold the joining of the chars and new line in new_input_list
      #5 for loop to loop through the user_input string
      #6 counts the number of chars by counting the number of loops
      #7 appends chars to list
      #8 enter condition that once 20 loops(chars) have passed
      #9 appends new line to list
      #10 resets the char_count to 0 so condition can be used on the next 20 chars
      #11 prints out the joined list to a string called user_new_input
      
      

      【讨论】:

        猜你喜欢
        • 2012-05-18
        • 2015-01-25
        • 2012-08-28
        • 2019-12-03
        • 2017-12-19
        • 2021-10-10
        • 2014-12-08
        • 2015-10-22
        • 2013-05-12
        相关资源
        最近更新 更多