1

i'm trying to center the text of a string but i can't do it. I checked mutiple posts and tried what they said, i don't get an error but the text is still aligned to the left. here the code and the str i want to center

while True:
        print ''
        while True:
                try:
                    userNum = float(raw_input('Enter the total of your bill: '))

                    if (userNum) > 0 and (userNum) != 0:
                        break
                    else:
                        print 'Oops!  That was no valid number.  Try again...'
Adrian Sultu
  • 330
  • 5
  • 16
  • 1
    your `try:` statement has no `except:` part. Where do you try to center something in this code. A `print` statement without a final `,` will start the next print on a new line, i.e. left aligned. – Anthon Mar 08 '13 at 19:21
  • it does have one, i just didn't paste it. – Adrian Sultu Mar 08 '13 at 20:24

2 Answers2

6

You could use str.format. The ^80 format tells Python to make the string 80 characters long, and to center the argument:

print('{:^80}'.format('Oops!  That was not a valid number.  Try again...'))

yields

               Oops!  That was not a valid number.  Try again...                
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Thank you! this worked but how would i apply this to that string? userNum = float(raw_input(('{:^80}'.format('Enter the total of your bill:')))) it seems to put spaces after the string too... but what if i want it just before and not after? – Adrian Sultu Mar 08 '13 at 19:27
  • @AdrianSultu: Use `^` to center the argument, `>` for right justification, `<` for left justification. The documentation of `str.format` is a little daunting at first (it is like an arcane mini-language), but it is so chock-full of goodies it is well worth taking the time to master. – unutbu Mar 08 '13 at 19:37
2

take a look at this str.center

PurityLake
  • 1,110
  • 10
  • 18