From http://pymbook.readthedocs.org/en/latest/modules.html
I've added some code to this code to make a little header for my code snippets as an exersise.

"""
Bars Module
============
This is an example module with provide different ways to print bars.
"""
def starbar(num):
    ''' (int) -> integer

    Prints a bar with *

    >>> bars.starbar(10)
    **********
    '''
    print('*' * int(num))

def hashbar(num):
    ''' (int) -> integer

    Prints a bar with #

    >>> bars.hashbar(10)
    ##########
    '''
    print('#' * int(num))

def simplebar(num):
    ''' (int) -> integer

    Prints a bar with -

    >>> bars.simplebar(10)
    ----------
    '''
    print('-' * int(num))

def lp_header():
    """
    Prints a header for my py files
    """
    hashbar(80)
    print "# Filename:\t\n# Copyright:\tLuke Pettit\n# Date:\t\t    /  /2013"
    hashbar(80)

and it prints this :-

################################################################################                                                                                          
# Filename:                                                                                                                                                               
# Copyright:    Luke Pettit                                                                                                                                               
# Date:             /  /2013                                                                                                                                              
################################################################################

What I would like to achieve is this:-

#-------------------------------------------------------------------------------                                                                                          
# Filename:                                                                                                                                                               
# Copyright:    Luke Pettit                                                                                                                                               
# Date:             /  /2013                                                                                                                                              
#-------------------------------------------------------------------------------

So putting a hash symbol and then a 79 line of - dashes
Can I somehow call two functions one after another and how would I format that
or do I rewite the code entirely?

Dani AI

Generated

Nice and simple — ’s quick concatenation is perfectly fine for a one-off. If you want something reusable (auto width, consistent padding, easy to call from scripts or to write to files) you can wrap the logic in a small builder that handles width detection, padding and returns a single string. That keeps printing/formatting separate from data, follows ’s advice about using the print function, and keeps the multi-line layout idea that showed but makes it a reusable utility.

def header_block(fields, width=None, left='#', fill='-'):
    import shutil
    if width is None:
        width = shutil.get_terminal_size((80, 20)).columns
    def make_line(text=''):
        base = f"{left} {text}".rstrip()
        return base.ljust(width)[:width]
    top = (left + fill * width)[:width]
    lines = [top]
    for name, value in fields.items():
        lines.append(make_line(f"{name}: {value}"))
    lines.append(top)
    return "\n".join(lines)

# example usage
meta = {'Filename': 'demo.py', 'Copyright': 'Luke Pettit', 'Date': '1/1/2013'}
print(header_block(meta))

Notes and troubleshooting:

  • The function falls back to 80 columns if terminal size can’t be read; pass an explicit integer for fixed-width headers.
  • It pads/truncates exactly to the chosen width so columns stay aligned; long values will be clipped.
  • For Python versions before 3.6 replace the f-strings with str.format() or simple concatenation; for scripts that must run under Python 2 keep from __future__ import print_function.
  • If you need the header written to a file, call file.write(header_block(meta) + '\n') instead of printing.
  • If using Unicode in names/filenames be aware that some terminals count display width differently; keep the header characters simple for portability.

The answer was as simple as

print('#' + '-' * (num-1))

I added this function to handle this situation

def hash_dashbar(num):
    ''' (int) -> integer

    Prints a bar with #

    >>> bars.hash_dashbar(10)
    #---------
    '''
    print('#' + '-' * (num-1))

It's a very good idea to use parenthesis in your print statements as if you were using a function. It teaches you python 3 at the same time. If you add the line

from __future__ import print_function

as the first statement of your module, it will turn print into a true function. Then you can use

print('#', '-' * num, sep='')

or

print('#', end = '') # don't print a newline
print('-' * num)

I am not such a friend of banners but here is one version for you to learn some other features of Python (as you did mention format in your title)

>>> def banner(filename, name, d, m, y=2013, width=80):
    print '#' * width
    print '''\
# Filename:     {filename}
# Copyright:    {name}
# Date:         {d}/{m}/{y}'''.format(filename=filename, name=name, d=d, m=m,y=y)
    print '#' * width


>>> banner('demo.py', 'Tony Veijalainen', 9, 9)
################################################################################
# Filename:     demo.py
# Copyright:    Tony Veijalainen
# Date:         9/9/2013
################################################################################
>>> 

Thanks pyTony and Gribouillis. I am learning P3. pyTony, this was exactly what I was heading for eventually.
Very much apperciated thanks to both of you.
Luke

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.