简体   繁体   English

填充右多行字符串

[英]Pad right multi-line string

After finding this code snippet from here 这里找到此代码片段后

'{0: <16}'.format('Hi')

I was able to right pad strings - which is what I'm after. 我能够正确填充字符串 - 这就是我所追求的。 I've written a function to deal with multi-line strings, but I a feeling there's a quicker, more Pythonic method: The strings get padded with "." 我已经编写了一个处理多行字符串的函数,但我觉得有一个更快,更Pythonic的方法:字符串用“。”填充。 just as an example. 仅作为一个例子。

#!/usr/bin/python

def r_pad_string (s):

  listy = s.splitlines()

  w = 0
  ss = ""

  for i in range(0, len(listy)):
    l = len(str(listy[i]))
    if  l > w:
      w = l

  for i in range(0, len(listy)):
    pad = str(listy[i]).ljust(w, ".")
    ss += pad + "\n"

  return  ss


myStr1 = "  ######\n"  \
         " ########\n" \
         "##  ##  ##\n" \
         "## ### ###\n" \
         "##########\n" \
         "##########\n" \
         "##  ##  ##\n" \
         "#   #   #"

myStr2 = """Spoons
  are
great!!!"""

print r_pad_string(myStr1)
print r_pad_string(myStr2)
def r_pad_string2(s, fillchar='.'):                    
    lines = s.splitlines()
    max_len = max(len(l) for l in lines)
    return '\n'.join(l.ljust(max_len, fillchar) for l in lines)

timings: 定时:

In [12]: %timeit r_pad_string(myStr1)
100000 loops, best of 3: 5.38 µs per loop

In [13]: %timeit r_pad_string2(myStr1)
100000 loops, best of 3: 3.43 µs per loop

In [14]: %timeit r_pad_string(myStr2)
100000 loops, best of 3: 2.48 µs per loop

In [15]: %timeit r_pad_string2(myStr2)
1000000 loops, best of 3: 1.9 µs per loop

So it's not that much faster, but a lot easier on the eyes. 所以它不是那么快,但在眼睛上更容易。

The max -function exists, which eliminates your first loop. max -function存在,这消除了你的第一个循环。 And join can be used to stick the lines together again: join可用于再粘在一起的线路:

def r_pad_string(s):
    lines = s.splitlines()
    width = max(len(l) for l in lines)
    return "\n".join(
        line.ljust(width, ".")
        for line in lines
    )

General remarks: indentation should be 4 spaces per level and variable names should be speaking. 一般说明:缩进应该是每个级别4个空格,并且应该说变量名称。 Iterating over lines can be done directly, not with the help of an index. 迭代线可以直接完成,而不是在索引的帮助下。 Use empty lines only, when it really helps readability. 当它确实有助于可读性时,仅使用空行。 The elements of listy are already strings, so no need to convert them to strings over and over again. listy的元素已经是字符串,所以不需要一遍又一遍地将它们转换为字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM