Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Spaces in string
#1
I am following Loop tutorials and in the exercises to try. Question 11 is to create a box of stars asking the user how high and wide they want the box.

My code creates:
******
*
*
*******
How do I create blank spaces before printing the last star to make the box complete?
I've input numbers for user to save typing each time I run the code.
print('*'*6, end = '\n')

for i in range (2):
    print ('*', end = '\n')
    
print('*'*6)
Thanks for looking.
Reply
#2
print('*'*6, end = '\n')
 
for i in range (2):
    print (f"*{' '*4}*", end = '\n')
     
print('*'*6)
Output:
****** * * * * ******
Reply
#3
Somewhat confusing using the asterisk * and the Python multiply symbol * together, poor chap may become confused!

I have always thought it weird that it is possible to multiply strings by a number, but you can!

I think we should use the IKEA principle, put everything in a flatpack for easy delivery and assemble at home!

Different characters have different widths, so we need an adjuster!

def boxit(wide, high, adjuster):
    flatpack =[]
    start = '+'  *  (wide + adjuster)
    flatpack.append(start)
    # use double underscore instead of space for better vizualisation
    line = '+'  + '__'  *  wide + '+'
    for h in range(high - 2):
        flatpack.append(line)
    flatpack.append(start)
    return flatpack

result = boxit(20, 20, 1)
# repeat the above until you get a nice box by changing the adjuster
# assemble the box at home
for r in result:
    print(r)
You could alter boxit() to take a symbol like @ and a spacer like ? if you wanted, just for fun, of course!

result = boxit(20, 20, 6, '@', '?')
As it is nearly Christmas, here a link to star pattern Python code.
Reply
#4
Thanks for both of your replies.
At the level I am at I will use Alex's solution.
I will copy and save Pedro's solution for when I better understand Python.
Here is my finished code.
width =  eval(input('How wide do you want the box? '))
height = eval(input('How high do you want the box? '))
space = width-2

print('-'*width, end = '\n')

for i in range (height):
    print (f"|{' '*space}|", end = '\n')
    
print('-'*width)
I do have one question what is the f doing in the print statement?
Reply
#5
One should never ever use eval() for unrestricted user input evaluation.

If user writes ‘os.system(‘rm -rf /’)’ then Python will use os.system to run rm -rf / and if there is no permission safeguards it will effectively perform full system wipe (so don’t try it on your machine).

This is extreme example and there are some safeguards available but usually there are bypasses for those safeguards as well.

As side remark: this code does not need eval() at all.
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
#6
Thanks for the warning. I did try to remove eval()
but then the program stopped working when I ran it.
How wide do you want the box? 6
How high do you want the box? 4
Traceback (most recent call last):
  File "C:\Users\anybl\Documents\Python Programs\Exercise 2.5\Ex2.5 Q11_Stars frame.py", line 3, in <module>
    space = width-2
TypeError: unsupported operand type(s) for -: 'str' and 'int'
Reply
#7
(Dec-18-2025, 02:24 PM)Mallard Wrote: Thanks for the warning. I did try to remove eval()
Use int() and can remove end = '\n' Python's print() function defaults to '\n'.
A Practical Guide to F-strings in Python
width =  int(input('How wide do you want the box? '))
height = int(input('How high do you want the box? '))

space = width - 2
print(f"{'-' * width}")
for i in range(height):
    print (f"|{' '*space}|")
print(f"{'-' * width}")
perfringo likes this post
Reply
#8
Thanks Snippsat.
So, I take it that int is integer, which is what we want the user to input?
I will go and read the link for F-strings in python.
Maybe the tutorial I'm following is a little out of date now.
Reply
#9
Once you have data, it is good to save it somewhere for later use. Here we just have a pattern, but maybe later you have some important stuff!

Save as a csv, or save as json. Both types are actually just simple text files.

Also new improved boxit()!

# maybe the adjuster must be negative
# depends on the relative widths of symbol and spacer 
# the Python module unicodedata gives info on the widths of characters
def boxit_symbols(wide, high, adjuster, symbol, spacer):
    flatpack =[]
    start = symbol *  (wide + adjuster)
    flatpack.append(start)
    line = symbol  + (spacer  *  wide ) + symbol
    for h in range(high - 2):
        flatpack.append(line)
    flatpack.append(start)
    return flatpack

result = boxit_symbols(20, 20, -8, '@',  '?')
for r in result:
    print(r)   
Save your data as csv:

import csv

# save 2 csv you can open a csv file with any text editor to view it
savepath = '/home/peterr/temp/csvs/boxit.csv'
with open(savepath, mode='w') as csvout:
    csv_writer = csv.writer(csvout, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    # give csv_writer a list of lists
    csv_writer.writerows(result)
Save your data as json:

import json

# save to json can also open in any text editor for viewing
savejson = '/home/peterr/temp/csvs/boxit.json'    
with open(savejson, "w") as json_file:
    json.dump(result, json_file, indent=4)

# reload the json
with open(savejson) as infile:
    res = json.load(infile)

for r in res:
    print(r)
As mentioned above better not to use eval()!
Reply
#10
Thanks for the reply Pedroski,
All helps with my learning and understanding of Python.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I want to validate that there is not more than two blank spaces in a string of charac jlpavon1987 4 4,708 Mar-29-2019, 10:49 PM
Last Post: woooee

Forum Jump:

User Panel Messages

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