Python Forum
Help with "surrounding" a string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with "surrounding" a string
#1
Hello, I am having difficulty with a homework assignment that asks me to code a print statement where the string input gets surrounded by asterisks. The question itself is... "Write a Python function banner that takes a string (say, str) and returns
a string that “surrounds” str with asterisks, as illustrated below:
>>> banner ("hello")
’*********\n* hello *\n*********\n’
>>> print (banner ("hello"))
*********
* hello *
*********

Right now, the code I have is:
def line(width,ch='*'):
return(width*ch+"\n")

I am asked to only use simple techniques that don't include iterators or other advanced features or libraries of Python. Thank you for any help you can provide!
Reply
#2
Please use python tags when posting code, so we can see the indentation. See the BBCode link in my signature for instructions.

You should pass the text to the function. Then figure out the width of the text within function. You do it this way because you need both the text and its width in the function. Then put the three parts together: width * (width + 4) asterisks, the original text between '* ' and ' *', and the row of asterisks again.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Below is one solution that works, just a number of simple
print statements in Python3

#!/usr/bin/env python
msg = input("Enter message:- ")
ch="*"
sp=" "
print(ch*(10+len(msg))) # print *
print(ch + (sp*(8+len(msg)))+ ch)
print("* " + msg + " *")
print(ch + (sp*(8+len(msg)))+ ch)
print(ch*(10+len(msg))) # print *
Below is the output:

Enter message:- Hello World
*********************
*                           *
*    Hello World     *
*                           *
*********************
You should be able to see how it works, it adds five "*" to beginning
and end of message, and adds a single "*" and four spaces to blank lines
Reply


Forum Jump:

User Panel Messages

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