1

How can I do variable string slicing inside string.format like this.

"{0[:2]} Some text {0[2:4]} some text".format("123456")

Result I want result like this.

12 Some text 34 some text

Rahul
  • 10,830
  • 4
  • 53
  • 88

1 Answers1

2

You can't. Best you can do is limit how many characters of a string are printed (roughly equivalent to specifying a slice end), but you can't specify arbitrary start or end indices.

Save the data to a named variable and pass the slices to the format method, it's more readable, more intuitive, and easier for the parser to identify errors when they occur:

mystr = "123456"
"{} Some text {} some text".format(mystr[:2], mystr[2:4])

You could move some of the work from that to the format string if you really wanted to, but it's not a huge improvement (and in fact, involves larger temporaries when a slice ends up being needed anyway):

"{:.2s} Some text {:.2s} some text".format(mystr, mystr[2:])
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271