哪个更好,字符串连接或替换? [英] which is better, string concatentation or substitution?
本文介绍了哪个更好,字符串连接或替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我最初的感觉是,连接可能需要更长时间才能取代,但它更容易阅读:
def p(self,paragraph):
self.source + =''< p>''+ paragraph +''< / p> \ n \ n'
vs 。
def p(self,paragraph):
self.source + =''< p>%s< / p> \ nn \\ n'%段落
这两种方式之间有偏好吗?
My initial feeling is that concatenation might take longer than
substitution, but that it is also easier to read:
def p(self, paragraph):
self.source += ''<p>'' + paragraph + ''</p>\n\n''
vs.
def p(self, paragraph):
self.source += ''<p>%s</p>\n\n'' % paragraph
Is there a preference between these two ways?
推荐答案
John Salerno写道:
John Salerno wrote:
我最初的感觉是连接可能需要更长时间才能取代
替换
看起来不那么:
leif @ ubuntu:〜
My initial feeling is that concatenation might take longer than
substitution
Doesn''t look that way:
leif@ubuntu:~
python -m timeit"''< p>%s< / p> \ n \'''% ''foobar''"
1000000循环,最佳3:0.6每循环usec
leif @ ubuntu:〜
python -m timeit "''<p>%s</p>\n\n'' % ''foobar''"
1000000 loops, best of 3: 0.6 usec per loop
leif@ubuntu:~
python -m timeit&q uot;''< p>''+''foobar''+''< / p> \ n \ n''"
1000000循环,最好的3:0.358每个循环使用
但它也更容易阅读:
python -m timeit "''<p>'' + ''foobar'' + ''</p>\n\n''"
1000000 loops, best of 3: 0.358 usec per loop
but that it is also easier to read:
我更喜欢字符串格式化以便于阅读,但它' '是b / b
个人偏好。
I prefer string formatting for readability, but it''s a matter of
personal preference.
这篇关于哪个更好,字符串连接或替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文