简体   繁体   中英

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'

你只需要在正确的位置使用括号

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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM