How can I add a parenthesis before the number 2500?

Viewed 75

I'm trying to output the following two lines of text:

The city with the most contracts is:

Chicago (2500 contracts)

this is the code I'm using:

a = 'Chicago'
b = 2500
print('The city with the most contracts is:')
print(a, b, 'contracts)')

the current output is:

The city with the most contracts is:
Chicago 2500 contracts)

How can I add a parenthesis before the number 2500?

I tried adding the parenthesis as a string, as in:

print('The city with the most contracts is:')
print(a, '(', b, 'contracts)')

but it adds an unwanted space between the parenthesis and the number 2500, looks like this:

The city with the most contracts is:
Chicago ( 2500 contracts)
6 Answers

The easiest way is with a formatting string.

print(f'{a} ({b} contracts)')

To handle manually the issue, you'd do

print(a, '(' + str(b), 'contracts)')

But you'd rather use the formatting solutions

print(f'{a} ({b} contracts)')

print('{} ({} contracts)'.format(a, b))

print('%s (%s contracts)' % (a, b))

For Python 3.6+:

print(f"{a} ({b} contracts)")

For a prior version:

print("{a} ({b} contracts)".format(a=a, b=b))

or

print("{} ({} contracts)".format(a, b))

I will not encourage to format using %.

This worked for me using string formatting

a = 'Chicago'
b = 2500

print("The city with the most contracts is:")
print("{} ({} contracts)".format(a,b))

Use the plus sign instead of the comma.

a = "Chicago"
b = 2500
print(a + ' (' + str(b) + ' contracts)')

The output was:

Chicago (2500 contracts)

This should work:

a = 'Chicago'
b = 2500
print('The city with the most contracts is:')

print(a + ' (' + str(b) + ' contracts)')
Related