0

I have some code similar to the following:

test_1 = 'bob'
test_2 = 'jeff'

test_1 += "-" + test_2 + "\n"

Output:

bob- jeff\n

I'd like to have the same functionality but using the .format method.

This is what I have so far:

test_1 = "{}{} {}\n".format(test_1, "-", test_2)

Which produces the same output, but is there a better/more efficient way of using .format. in this case?

2
  • 5
    Do you need to have the delimiter parameterized..could it be inside the format string? E.g.: "{}- {}\n".format(test_1, test_2)?.. Commented Oct 19, 2016 at 18:17
  • 1
    Could also use '- '.join((test_1, test_2)) + '\n' Commented Oct 19, 2016 at 18:20

1 Answer 1

1

''.join is probably fast enough and efficient.

'-'.join((test_1,test_2))  

You can measure different methods using the timeit module. That can tell you which is fastest

This is an example of how timeit can be used:-

>>> import timeit
>>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
0.8187260627746582
Sign up to request clarification or add additional context in comments.

4 Comments

@tinySandy I don't see efficient way of using format, other that what Proletariat came up with. So i just posted another efficient way of doing this. :)
i wouldn't post anything since it's not related to what OP was asking
I appreciate the response but it's not using .format as @tinySandy said.
@Proletariat Im sorry, I did not read your question properly. I thought you were just asking if there was any other "better/more efficient" method.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.