开发者

What is the difference between python string concatenation and string insertion

开发者 https://www.devze.com 2023-03-07 07:59 出处:网络
I want to know wha开发者_Python百科t is the diff between two string operations in python filestamp = time.strftime(\'%Y-%m-%d\')

I want to know wha开发者_Python百科t is the diff between two string operations in python

filestamp = time.strftime('%Y-%m-%d')
database = "mysql";

Between this

filename = "/home/vmware/%s-%s.sql" % (database, filestamp)

and

filename = "/home/vmware/"+database+"-"+filestamp+".sql"


String interpolation using the '%' operators take the types of the interpolated values into account. String concatentation using the '+' will only work for strings. So you can't mix strings with numbers using the '+' operator. In general: string interpolation is what you want - at least for building strings from other values especially if you deal with different types.


The first approach creates 1 string where as the second creates temporary strings which is wasted. Strings in python are immutable, once created you cannot modify it.

0

精彩评论

暂无评论...
验证码 换一张
取 消