JakeM
JakeM

Reputation: 71

How to combine text in print

I'm trying to print everything my variable contains together, but instead of this

-1.5, -2.0

I get

('-', '1.5', '-', '2.0')

My code is

import re
numbers = "Number is -1.75"
textnumber = re.findall(r'(\d+(?:\.\d+)?)', numbers)[0]
number = float(textnumber)
number1 = '-', str(number - 0.25), '-', str(number + 0.25)
print(number1)

How can I combine them so output looks like

-1.5, -2.0

Upvotes: 0

Views: 158

Answers (3)

Adon Bilivit
Adon Bilivit

Reputation: 27008

You should use a regular expression that can handle (optional) +- signs

For example:

from re import compile

p = compile(r'[-+]?(?:\d*\.*\d+)')
numbers = 'Number is -1.75'

if s := p.search(numbers):
    n = float(s[0])
    print(n + 0.25, n - 0.25, sep=', ')
else:
    print('No matching number')

Output:

-1.5, -2.0

Upvotes: 1

lemon
lemon

Reputation: 15482

You should embed your negative sign inside the regex, as an optional sign (hence invert the position of -0.25 and 0.25). Then avoid crafting strings of numbers, and use them in the print directly.

import re

numbers = "Number is -1.75"
textnumber = re.search(r'-?\d+(?:\.\d+)?', numbers)[0]
number = float(textnumber)

print(f'{number + 0.25}, {number - 0.25}')

Output:

-1.5, -2.0

Check the demo here.

Upvotes: 2

Florent Monin
Florent Monin

Reputation: 1332

When you use commas ,, you create a tuple (what is being printed between parenthesis). To perform string concatenation, you need to use +

number1 = '-' + str(number - 0.25) + ', -' + str(number + 0.25)

Note that you can use f-strings for that purpose, like so:

number1 = f"-{number - 0.25}, -{number + 0.25}"

Upvotes: 2

Related Questions