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?

Proletariat
  • 213
  • 5
  • 10

1 Answers1

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
Nihal Rp
  • 484
  • 6
  • 15
  • @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. :) – Nihal Rp Oct 19 '16 at 18:46
  • i wouldn't post anything since it's not related to what OP was asking – midori Oct 19 '16 at 18:47
  • I appreciate the response but it's not using `.format` as @tinySandy said. – Proletariat Oct 19 '16 at 20:34
  • @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. – Nihal Rp Oct 19 '16 at 20:55