简体   繁体   中英

How do I format code to print with the same width every time?

I am making a game and am wondering if there is a way to have python print a map that can look something like this, and not look bad when it prints the end result? It's supposed to be a map of a room in a text-based game. Can I format it with a command to do this? I've only tried:

print("|------------------------------|")#print room map
print("|   [Chest]                 |")
print("|                            _ |")
print("|                       Door|")
print("|                             _|")
print("|   [Table]                 |")
print("|  (You)                     |")
print("|------------------------------|")#print room map

Predictably, the above prints:

>>> print_room()
|------------------------------|
|   [Chest]                 |
|                            _ |
|                       Door|
|                             _|
|   [Table]                 |
|  (You)                     |
|------------------------------|

However, in my IDE each of those lines looks like they terminate at the same place. How do I write the code such that I can guarantee the lines are all the same width? I want it to print to look like this:

|---------------------|
|                     |
|                     |
|                     |
|                     |
|---------------------|

What text editor are you using to write your code? I suspect you're using something like Word or Wordpad which use proportional fonts.

I'd recommend switching to a dedicated code editor such as Notepad++ or UltraEdit , or, worst case, Notepad. An editor that is made for text files and uses a fixed with font such as Courier. That will make lining up the lines of your map much easier, among many other benefits.

Notice how Stack Overflow uses a fixed with font? It shows that you don't have the right number of spaces on each line. Your code, correctly spaced, would look like you want:

print("|------------------------------|")#print room map
print("|   [Chest]                    |")
print("|                            _ |")
print("|                          Door|")
print("|                             _|")
print("|   [Table]                    |")
print("|  (You)                       |")
print("|------------------------------|")#print room map

You can try using a multiline string, ie. a string enclosed with triple quotation marks can extend over one line. So you can do something like:

map = """
                        |---------------------|
                        |                     |
                        |                     |
                        |                     |
                        |                     |
                        |---------------------|"""
print(map)

Is that what you mean?

Edit: In your code, it also appears you haven't adjusted the rows with the correct number of spaces after adding "table" etc. If you have the same code, but add some more spaces to it, you'll be able to make it work in your way as well. You are saving this in a script and then running it, correct? Not in trying it in the interpreter? Finally, pro tip: in the terminal, each character takes up a space of the same width, ie.
..... will be the same width as
MMMMM because in each case it's the same number of characters.

Your basic problem is that each line must be the same length. Things that can interfer with this:

  • Font may display different characters with different widths. Typically 'Terminal' windows will use fixed-width fonts: every character, space, etc. has exactly the same width. 'Higher level' editors (such as Word ) will use variable-width fonts, because it will be more aesthetically pleasing and has a wider range of aesthetic uses.
  • Things you've done to the string may change the actual length. As you can see in the provided example, different numbers of characters will display at different widths. Thus, your programming challenge is to ensure that the width of each line is the same.

What you should do to ensure this is get clever with how you build your strings.

Lets start with a basic room string, a chest and a door:

room = "|                     |"
chest = "[Chest]"
door = "Door"

Now lets write a function that inserts an object at a particular position:

def insert_object(new_object: str, position: int) -> str:
    room_start = room[0:position]
    end_position = position + len(new_object)
    room_end = room[end_position:]
    new_room = room_start + new_object + room_end
    return new_room

This gets us a result like this:

>>> room = "|                     |"
>>> chest = "[Chest]"
>>> door = "Door"
>>> def insert_object(new_object: str, position: int) -> str:
...     room_start = room[0:position]  # Gets the part of the room before the 'object'
...     end_position = position + len(new_object)  # Gets the position after the object 'ends'
...     room_end = room[end_position:]  # Gets the part of the room after the object 'ends'
...     new_room = room_start + new_object + room_end  # Pieces these parts together, with the object in the middle
...     return new_room  # Returns the result
... 
>>> x = insert_object(chest, 3)
>>> print(x)
'|  [Chest]            |'

Do that for each 'row' of your room you want to insert an item, and you can maintain your widths!

room = "|                     |"
chest = "[Chest]"
door = "Door"
wall = "---------------------"
trap = "-"
you = "You"
table = "[Table]"

def print_room():
    print(insert_object(wall,1))
    print(insert_object(chest,3))
    print(insert_object(trap,20))
    print(insert_object(door,18))
    print(insert_object(trap,21))
    print(insert_object(table,4))
    print(insert_object(you,3))
    print(insert_object(wall,1))

Resulting in:

>>> print_room()
|---------------------|
|  [Chest]            |
|                   - |
|                 Door|
|                    -|
|   [Table]           |
|  You                |
|---------------------|

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM