TechnologicalGenious
TechnologicalGenious

Reputation: 37

how to use str.format() with variables in python

I am wanting to use str.format() with the variable randomOne, since %s doesn't seem to be working for me:

print('The number generated between %s and %s is' + number) % (randomOne, randomTwo)

And I get this error:

TypeError: unsupported operand type(s) for %: 'nonetype' and 'tuple'

Upvotes: 0

Views: 159

Answers (2)

rlms
rlms

Reputation: 11060

You need to do the formatting operation on the string, not the operation of printing the string. That is the cause of your current problem. If you want to use str.format in this case you would do this:

print('The number generated between {} and {} is {}'.format(randomOne, randomTwo, number))

In the event you want to stick with old style string formatting (which I wouldn't advice), you would do this:

print('The number generated between %s and %s is %s' % (randomOne, randomTwo, number))

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239473

You just have to use the brackets at the right place

print('The number generated between %s and %s is %d' % (randomOne, randomTwo, number))

Upvotes: 1

Related Questions