python3.4.2 如何用文本和变量赋值一个字符串

python3.4.2 how to assign a string with texts and variables

我想以两个单词后跟相应变量的格式分配字符串,例如:

"newstring = 'length', length, 'slope', slope"

我会在 text = Text(point1, newstring) 这样的文本函数中使用它 有办法实现吗?

使用format:

>>> length=22
>>> slope=45
>>> newstring='length {}, slope {}'.format(length, slope)
>>> newstring
'length 22, slope 45'

格式化函数或格式化方法有一组丰富的format specifications允许字符串以所需的方式呈现:

>>> 'Feeling hexey 0x{:X} and octally 0{:o} for decimal {}'.format(12, 12, 12)
'Feeling hexey 0xC and octally 014 for decimal 12'
>>> "Lot's o decimals: {:0.30f}".format(.5)
"Lot's o decimals: 0.500000000000000000000000000000"

您也可以将类似的字符串类型连接在一起:

>>> 'length ' + str(length) + ' slope ' + str(slope)
'length 22 slope 45'

或使用旧的 'meatball' 运算符:

>>> 'length %d, slope %d' % (length, slope)
'length 22, slope 45'

但那些不如 format 优雅...