2

I am a newbie to Python and trying to use print and for loop to print a pattern like following, where the width of block depends on the characters I want to enter, i.e. width of block and surrounding lines increase dynamically with length of string say, ABCDEFGHI.. :

┏━━━━━━━━━━┓
┃  ABCDE   ┃
┗━━━━━━━━━━┛

I am trying to iterate over the characters of string like -

name = "abcdefghi"

for i in name:
    print("━",end="")

print()

for j in range(1):
    print("┃"+" "*(len(name)-1)+"┃")

for k in name:
    print("━",end="")

which gives me an output like,

━━━━━━━━━━━━
┃           ┃
━━━━━━━━━━━━
  1. How can I use multiple loops to END the lines? (such that the pattern does not look like an open-ended box)
  2. Is there someway I can start the second loop index -1 than the line ━━━ pattern?

Need suggestions on what to try?

s_neenu
  • 95
  • 2
  • 7
  • Are you trying to just put the name in the box like the first example? – alani Sep 02 '20 at 17:26
  • The problem is with the characters you are printing, not the loops. I suggest you find the corner characters in order to print what you want. – Code-Apprentice Sep 02 '20 at 17:29
  • https://stackoverflow.com/questions/20756516/python-create-a-text-border-with-dynamic-size – zvi Sep 02 '20 at 17:30

3 Answers3

5

There are characters like '┏' in your sample so you need to consider them while designing your logic:

name = "abcdefghi"
width = len(name) + 4
print('┏' + "━"*width + "┓")
print('┃' + name.center(width) + '┃')
print('┗' + "━"*width + "┛")
┏━━━━━━━━━━━━━┓
┃  abcdefghi  ┃
┗━━━━━━━━━━━━━┛
Asocia
  • 5,935
  • 2
  • 21
  • 46
2

You can first built the complete string and then print it

name = "abcdefghi"

hh = (len(name)+4)*"━" # horizontal line, using "string multiplication"
box = f"┏{hh}┓\n┃  {name}  ┃\n┗{hh}┛" # using f-string substitution
print(box)
┏━━━━━━━━━━━━━┓
┃  abcdefghi  ┃
┗━━━━━━━━━━━━━┛
Jan Stránský
  • 1,671
  • 1
  • 11
  • 15
1

If you want to write the name in a box, then you do not need the for loops. You can use "━" * len(name) for the variable length string in the way that your existing code is using " "*(len(name)-1)

name = "abcdefghi"

print("┏━" + "━" * len(name) + "━┓")
print("┃ " + name + " ┃")
print("┗━" + "━" * len(name) + "━┛")

giving:

┏━━━━━━━━━━━┓
┃ abcdefghi ┃
┗━━━━━━━━━━━┛

And for a slightly wider box as in the question, it is probably easiest just to hard-code some slightly longer strings at the edges:

print("┏━━" + "━" * len(name) + "━━┓")
print("┃  " + name + "  ┃")
print("┗━━" + "━" * len(name) + "━━┛")

giving:

┏━━━━━━━━━━━━━┓
┃  abcdefghi  ┃
┗━━━━━━━━━━━━━┛
alani
  • 12,573
  • 2
  • 13
  • 23