1

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 "." 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)
Community
  • 1
  • 1
Mr Mystery Guest
  • 1,308
  • 12
  • 42

2 Answers2

2
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.

Ilja Everilä
  • 40,618
  • 6
  • 82
  • 94
1

The max-function exists, which eliminates your first loop. And join can be used to stick the lines together again:

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. 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.

Daniel
  • 39,063
  • 4
  • 50
  • 76