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

3
  • 1
    why dont simple "Some text {0} some text".format("123456"[2:4])? Commented Nov 29, 2016 at 4:04
  • Please see the edit. Actual final string is bit complex. Commented Nov 29, 2016 at 4:06
  • 4
    I think you can't Commented Nov 29, 2016 at 4:09

1 Answer 1

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:])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.