2

I couldn't put my question into words accurately, so I am sorry if this question has been answered. I will try to explain it in code.

String_0 = "Car"
String_1 = "Bus"
String_2 = "Plane"
for i in range(3):
    print(String_i)

I want the output like this:

Car
Bus
Plane

Edit: My original code is this:

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]


def tablePrinter(tableData):
    Space_0 = 0
    Space_1 = 0
    Space_2 = 0
    for i in range(len(tableData[0])):
        if len(tableData[0][i]) > Space_0:
            Space_0 = len(tableData[0][i])
    for i in range(len(tableData[1])):
        if len(tableData[1][i]) > Space_1:
            Space_1 = len(tableData[1][i])
    for i in range(len(tableData[0])):
        if len(tableData[2][i]) > Space_2:
            Space_2 = len(tableData[2][i])
    for i in range(len(tableData[0])):
        print(tableData[0][i].rjust(Space_0), tableData[1][i].rjust(Space_1),
              tableData[2][i].rjust(Space_2), end = "")
        print()
        
tablePrinter(tableData)

My output is this:

  apples Alice  dogs
 oranges   Bob  cats
cherries Carol moose
  banana David goose

This output is what I wanted. But I want to simplify code by editing this part:

for i in range(len(tableData[0])):
            print(tableData[0][i].rjust(Space_0), tableData[1][i].rjust(Space_1),
                  tableData[2][i].rjust(Space_2), end = "")
            print()

I want a structure like this:

for i in range(len(tableData[0])):
        for k in range(len(tableData)):
            print(tableData[k][i].rjust(Space_k), end = " ")
        print()

I tried to apply your advices to this part. I tried to add globals(), locals() in front of tableData[k][i].rjust(Space_k), or in front of Space_k; tried {} .format structure, tried to use list, but I couldn't solve.

Edit2: So I managed to solve the problem with using lists. Thanks to everyone.

spaceList = [Space_0, Space_1, Space_2] # I added this to function.

Instead of this line in last part,

print(tableData[k][i].rjust(Space_k), end = " ")

I used this:

print(tableData[k][i].rjust(spaceList[k]), end = " ")
Albatros
  • 23
  • 5

5 Answers5

1

You can put them inside a list and iterate it over.

for vehicle in ['Car', 'Bus', 'Plane']:
    print(vehicle)

Or if you need to access them by index, you can still use list.

vehicles = ['Car', 'Bus', 'Plane']

for i in range(len(vehicles)):
    print(vehicles[i])
sanitizedUser
  • 1,723
  • 3
  • 18
  • 33
  • @Albatros Does this not answer your updated question as well? The lesson is, don't use individual variables like `Space_0; Space_1; Space_2`, use a list instead. – wjandrea Jul 15 '21 at 17:48
  • @wjandrea I managed to solve the problem using lists. I am confused how I couldn't apply your advice to my code yesterday. Thank you so much! – Albatros Jul 16 '21 at 11:11
0

This must be very simple to solve as below:

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]
             
for a, b, c in zip(*tableData):
    print(a, b, c)

If your number of rows are not known then you can do as below:

for a in zip(*tableData):
    print(" ".join(a))
0

Welcome to SO and to Python! Looking at your original question, Python has excellent facilities for iterating over collections. If you have data like:

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

And you want to print it in transposed form, the simplest way I can think of would be:

for tup in zip(*tableData):
    print(" ".join(tup))

Unpacking this:

  • The * operator tells python, essentially, to unpack the list tableData and present it to the zip function as a series of distinct arguments. (there's more to be said about this operator, but this isn't the place - see for example Trey Hunner's article)
  • The zip function accepts two or more iterables i1, i2, ..., and produces a sequence of tuples (i1[0], i2[0], ...), (i11, i21, ...), etc. In your case, we get ("apples", "Alice", "dogs"), ("oranges", "Bob", "cats"), etc
  • The join function on some string s takes a sequence of strings and composes a string by gluing them together with the string s, in this case I've used the string " "

This is not exactly what you've asked for - it looks like you'd like the strings presented in a nicely justified table - but it should point you in the right direction.

Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38
0

Generally when you want to run similar code on multiple pieces of data, you should store the data in a list or dict and loop over that. That will make your code shorter, more readable and easier to maintain.

In your case, your code can be rewritten like this:

def tablePrinter(tableData):
    space = [0, 0, 0]
    for j in range(len(space)):
        for i in range(len(tableData[j])):
            if len(tableData[j][i]) > space[j]:
                space[j] = len(tableData[j][i])
    for i in range(len(tableData[0])):
        for j in range(len(space)):
            print(tableData[j][i].rjust(space[j]), end=" ")
        print()

Or this can be simplified further, like this:

def tablePrinter(tableData):
    space = [0, 0, 0]
    for j in range(len(space)):
        space[j] = max(len(cell) for cell in tableData[j])
    for i in range(len(tableData[0])):
        for j in range(len(space)):
            print(tableData[j][i].rjust(space[j]), end=" ")
        print()

or this:

def tablePrinter(tableData):
    space = [
        max(len(cell) for cell in row)
        for row in tableData
    ]
    for i in range(len(tableData[0])):
        for j, width in enumerate(space):
            print(tableData[j][i].rjust(width), end=" ")
        print()
Matthias Fripp
  • 17,670
  • 5
  • 28
  • 45
-1

All the variables will be in the globals() structure.. globals() call will return a dictionary. so you can index it with variable name as below:

String_0 = "Car"
String_1 = "Bus"
String_2 = "Plane"
for i in range(3):
    print(globals()["String_{}".format(i)])

you can switch to locals() or globals() based on where you are..