James Pritchard
James Pritchard

Reputation: 79

How to remove space between $ and numbers in python

I am having a bit of trouble with an assignment in python. This is my first assignment so please go easy on me.

I have this line:

print('You can save a total of $',saved,'over',number_of_weeks,'weeks.')

The output is:

You can save a total of $ 5200 over 52 weeks.

How do I go about removing the space between the $ and 5200.

Please remember this is for an assignment, so a general answer would help me more than a specific answer (Please give me a hint, not the complete answer). This will help me to learn by myself. I just don't know where to start the problem solving process.

Upvotes: 0

Views: 8553

Answers (4)

Sakib Ahammed
Sakib Ahammed

Reputation: 2480

you can also use like C language.

print('You can save a total of $%d' %saved + ' over %d' %number_of_weeks + 'weeks.')

Upvotes: 0

awesoon
awesoon

Reputation: 33701

You could use str.format method:

In [1]: saved = 42
In [2]: number_of_weeks = 3.14159
In [3]: print('You can save a total of ${} over {} weeks.'.format(saved, number_of_weeks))
You can save a total of $42 over 3.14159 weeks.

It is also supports named arguments to make your code more readable:

In [5]: print('You can save a total of ${saved} over {weeks} weeks.'.format(saved=saved, weeks=number_of_weeks))
You can save a total of $42 over 3.14159 weeks.

Upvotes: 2

s-ol
s-ol

Reputation: 1754

In your current version, you let print handle multiple strings. That means that whatever is between them is managed by print.

What you need to do is turn those multiple strings into a single one that is formatted the way you like it.

You have multiple options here, either string concatenation ("abc" + "DEF") or string formatting.

Good luck on your journey into programming!

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174826

Convert the type of saved variable to string and add a concatenation operator + before that.

print('You can save a total of $'+str(saved),'over',number_of_weeks,'weeks.')

Example:

>>> saved = 123
>>> nu = 4
>>> print('You can save a total of $'+str(saved),'over',nu,'weeks.')
You can save a total of $123 over 4 weeks.

Upvotes: 0

Related Questions