开发者

Refer to same input multiple times in string replacement?

开发者 https://www.devze.com 2023-02-25 04:40 出处:网络
I need to print something like this \"a=name1,b=name2,c=name1,d=name2\" While I have name1 and name2 in variable n1 n2

I need to print something like this

"a=name1,b=name2,c=name1,d=name2"

While I have name1 and name2 in variable n1 n2

n1="name1"
n2="name2"

what I am trying to do

"a=%s,b=%s,c=%s,d=%s" % (n1,n2,n1,n2)

Is there a better way than this? way to avoid n1,n2,n1,n2开发者_如何学Go ?

with python 3 ?

and what if

print sys.version_info
(2, 1, 0, 'final', 0) 


"a=%(name1)s,b=%(name2)s,c=%(name1)s,d=%(name2)s" % {'name1': n1, 'name2': n2}


As long as the tuple is simply duplicated you can simplify by using tuple multiplication, otherwise use the dictionary interpolation shown in the other answer or use string.format.

(n1, n2, n1, n2) == (n1, n2) * 2

Example of using format:

"a={0}, b={1}, c={0}, d={1}".format(name1, name2)

Alternatively you could use string.replace:

"a=n1, b=n2, c=n1, d=n2".replace('n1', name1).replace('n2', name2)

But this is error-prone, to say the least.

0

精彩评论

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