user1804933
user1804933

Reputation: 453

Best way to add a "+" and "-"?

What is the best way to display either a + in front, for a float? Lets say if a user inputs the number "10". I want to have a "+" appear in front of it since it is a positive number. If it were a negative number then I would leave it as it is.

Would I have to use an if statement and then convert it to a string and then add in the + sign? Or is there an easier way?

Upvotes: 1

Views: 97

Answers (3)

umutberkbilgic
umutberkbilgic

Reputation: 62

The first thing I thought:

userInput=int(input("Enter number: "))
if userInput > 0:
    print ("+"+userInput)
else:
    pass

Formatting is just the way to go though, faster and cleaner.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124090

Use the format() function:

>>> format(10, '+f')
'+10.000000'
>>> format(-10, '+f')
'-10.000000'
>>> format(3.14159, '+.3f')
'+3.142'

See the Format Specification Mini-Language for the specific formatting options; prepending a number format with + makes it include a plus for positive numbers, - for negative. The last example formats the number to use 3 decimals, for example.

If you need to remove the negative sign, you'd have to do so explicitly using .lstrip():

>>> format(10, '+f').lstrip('-')
'+10.000000'
>>> format(-10, '+f').lstrip('-')
'10.000000'

but that'd be quite confusing a specification to read, in my opinion. :-)

Upvotes: 2

Jon Clements
Jon Clements

Reputation: 142216

Use formatting - and then remove any leading - from the result:

print format(10, '+').lstrip('-')

Upvotes: 0

Related Questions