Python Forum
Output String Padding help
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Output String Padding help
#1
Hello, I'd like to make my code output

10
10
0000000abc
abc0000000
What I'm I doing wrong with my code right now. All suggestions would be very much appreciated!
Here is my code

def pad_string(data, size, padding_character=' ', direction='left'):
    """This new function will determine if it will pad to the left or the right by using an if statement."""
    if direction == 'left':
        data = data.rjust(size, padding_character)
    elif data == 'right':
        data = data.ljust(size, padding_character)
    return data

def pad_left(data, size, padding_character=' '):
    """This new function will call pad_string and use it to pad to the left"""
    result_left = pad_string(data, size, padding_character, 'left')
    return result_left


def pad_right(data, size, padding_character=' '):
    """This new function will call pad_string and use it to pad to the left"""
    result_right = pad_string(data, size, padding_character, 'right')
    return result_right


# Output Test Code
print(len(pad_left('abc', 10)))
print(len(pad_right('abc', 10)))
print(pad_left('abc', 10, '0'))
print(pad_right('abc', 10, '0'))
Reply
#2
I added between vertical bars to emphasise effect
>>> # Pad left 10
>>> print(f"|{'abs':10}|")
|abs       |
>>>
>>> # pad right 10
>>> print(f"|{'abs':>10}|")
|       abs|
>>>
>>> # zeroes to right
>>> print(f"|abc{0:07}|")
|abc0000000|
>>>
>>> # zeroes to left
>>> print(f"|{0:07}abc|")
|0000000abc|
>>>
Reply
#3
In the function pad_string() look at the if conditions. What are you testing there? :-)
Reply
#4
Strings have also method for filling in zeros (fills into left side): str.zfill()

>>> s = 'abc'                                                                              
>>> s.zfill(len(s))                                                                        
'abc'
>>> s.zfill(10)
'0000000abc'
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Pyplot line color and spacing/padding metalray 0 2,693 May-26-2017, 08:39 AM
Last Post: metalray

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020