Reputation: 13
With C like formatting we can put just a slice of the string argument within the string. For example, this:
print "I just love %.4s." %('cats and dogs')
will print this:
I just love cats.
Is there an equivalent way to do this using format() ?
Upvotes: 0
Views: 63
Reputation: 812
You can use:
print("I just love {:.4}".format('cats and dogs'))
https://pyformat.info/ - this site is an excellent resource to compare how to use format
with "old style" format.
Upvotes: 0
Reputation: 414
In most cases %-based formatting translates into {}-based formatting by adding a colon.
print "I just love %.4s." %('cats and dogs')
is equivalent to:
print "I just love {:.4s}.".format('cats and dogs')
You may omit the s
in brackets, like this:
print "I just love {:.4}.".format('cats and dogs')
Upvotes: 0
Reputation: 3525
Take a look here.
>>> print "I just love {:.4}.".format('cats and dogs')
I just love cats.
Upvotes: 1
Reputation: 7850
Sure, you can use basically the same format:
>>> print('I just love {0:.4}.'.format('cats and dogs'))
I just love cats.
Upvotes: 2