Python Forum
Help with "surrounding" a string - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Help with "surrounding" a string (/thread-5750.html)



Help with "surrounding" a string - jsirota - Oct-19-2017

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!


RE: Help with "surrounding" a string - ichabod801 - Oct-19-2017

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.


RE: Help with "surrounding" a string - cygnus_X1 - Oct-19-2017

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