user1934887 user1934887 - 6 months ago 52
Python Question

Slicing strings in str.format

I want to achieve the following with


x,y = 1234,5678
print str(x)[2:] + str(y)[:2]

The only way I was able to do it was:

print '{0}{1}'.format(str(x)[2:],str(y)[:2])

Now, this an example and what I really have is a long and messy string, and so I want to put slicing inside the
. I've studied the docs, but I can't figure out the correct syntax. My question is: is it possible to slice strings inside a replacement field?


No, you cannot apply slicing to strings inside a the replacement field.

You'll need to refer to the Format Specification Mini-Language; it defines what is possible. This mini language defines how you format the referenced value (the part after the : in the replacement field syntax).