Formatting the opposite of some numbers, with decimal alignment Background

I have a list of strings containing numbers. Each string is 8 characters long. For example :

'-123.456'
' -12.345'
'  -1.234'
' 123.456'
'  12.345'
'   1.234'


The longest number possible is ' 999.999' ; the smallest number is '   0.000' and there always are 3 numbers in the decimal.

What I want to do is compute the opposite of each number, and return it as a string of length 8, with the opposite sign next to the number.

For example :

'-123.456' should yield ' 123.456'
' -12.345' should yield '  12.345'
'  -1.234' should yield '   1.234'
' 123.456' should yield '-123.456'
'  12.345' should yield ' -12.345'
'   1.234' should yield '  -1.234'


What I did

I wrote the following code, which works :

def opposite(x):
    if x.startswith('  -'):
        xopp = '   ' + x[3:]
    elif x.startswith(' -'):
        xopp = '  ' + x[2:]
    elif x.startswith('-'):
        xopp = ' ' + x[1:]
    elif x.startswith('   '):
        xopp = '  -' + x[3:]
    elif x.startswith('  '):
        xopp = ' -' + x[2:]
    elif x.startswith(' '):
        xopp = '-' + x[1:]
    return xopp


My question

I feel like this code is completely "unpythonic" and could be replaced by a one-liner. So the question is: does anyone have an idea to make it more pythonic or even a one-liner ?
There are only really two things you need here.


float. Which allows you to convert the input to a floating point number. If you change to needing more precision or larger numbers, decimal would be a better choice - thanks @200_success. And,
str.format. Which uses the Format String Syntax. Which you can use pad the left with spaces, so the output has a width of eight. {: &gt;8}. This however needs to be adjusted for your "there always are 3 numbers in the decimal" requirement, and so you can force this too with {: &gt;8.3f}.


And so I'd use:

def opposite(x):
    return '{: &gt;8.3f}'.format(-float(x))




If however you don't want to use float then you can use str.lstrip. With just one if-else:

def opposite(x):
    x = x.lstrip()
    if x.startswith('-'):
        x = x[1:]
    else:
        x = '-' + x
    return '{: &gt;8}'.format(x)