使用字符串替换组合字符串 - python

时间:2010-10-07 17:10:20

标签: python syntax

嘿伙计们,我想执行以下操作:

b = 'random'

c = 'stuff'

a  = '%s' + '%s' %(b, c)

但是我收到以下错误:

TypeError: not all arguments converted during string formatting

你们中的任何一个人都知道这样做吗?

3 个答案:

答案 0 :(得分:4)

'%s%s' % (b, c)

b + c

或newstyle format方式

'{0}{1}'.format(a, b)

答案 1 :(得分:1)

取决于您的需求:

>>> b = 'random'
>>> c = 'stuff'
>>> a  = '%s' %b + '%s' % c
>>> a
'randomstuff'
>>> 

>>> b + c
'randomstuff'
>>> 
>>> z = '%s + %s' % (b, c)
>>> z
'random + stuff'
>>> 

答案 2 :(得分:1)

由于运算符优先级,您的程序首先尝试将b和c替换为第二个'%s'。因此,用+分割这些字符串是没有意义的,最好这样做 a = '%s %s' % (b,c)