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 ?