Search code examples
pythonstringcentering

How can I center an integer variable in a string?


This is what I'm trying to do:

   Time        Distance
----------    ----------
    1              100
    2              200

I've tried:

count = 1
print('   Hour   ' + '\t' + ' Distance ')
print('----------' + '\t' + '----------')
while count <= timeTraveled:
print(str.center(10[str(count)]) + '\t' + str.center(10[str((speedOfVehicle * count))]))
count = count + 1

No matter how much I try to make my variables a string for formatting purposes I always encounter:

TypeError: 'int' object is not subscriptable

Solution

  • I think I see your problem: you've mistaken the meta-syntax of documentation for Python syntax.

    When a document describes a command with optional fields, brackets denote the option parts. This description style is at least 45 years old, dating back to the days when IBM drove all things computer in the western hemisphere. For help in writing your command, see the examples farther down.

    In your case, you need something like

    print(str(count).center(10))
    

    This is a method of the string class; it operates on the string with which you call it. In your case, that string is str(count). Can you follow the rest from there?