Zac*_*Zac 2 python string string-concatenation string-formatting
因此,我正在用Python 3.4编写一个文本游戏,该游戏print()经常需要使用该函数来向用户显示变量。
我一直使用的两种方法是使用字符串格式设置和字符串连接:
print('{} has {} health left.'.format(player, health))
Run Code Online (Sandbox Code Playgroud)
和,
print(player + ' has ' + str(health) + ' health left.')
Run Code Online (Sandbox Code Playgroud)
那么哪个更好呢?它们既具有可读性,又能快速键入,并且性能完全相同。哪一个是Pythonic,为什么?
问了一个问题,因为我在与Java无关的Stack Overflow上找不到答案。
取决于您的字符串有多长以及有多少个变量。对于您的用例,我相信string.format它会更好,因为它具有更好的性能并且看上去更清晰易读。
有时,对于较长的字符串而言,它+看起来更干净,因为变量的位置保留在字符串中应保留的位置,并且您无需四处移动即可将位置映射{}到相应的变量。
如果您可以升级到Python 3.6,则可以使用更新的,更直观的字符串格式语法,如下所示,并且兼具两全:
player = 'Arbiter'
health = 100
print(f'{player} has {health} health left.')
Run Code Online (Sandbox Code Playgroud)
如果字符串很大,我建议使用模板引擎Jinja2(http://jinja.pocoo.org/docs/dev/)或类似的东西。
参考:https : //www.python.org/dev/peps/pep-0498/
format() 更好:
这取决于您要组合的对象的数量和类型,以及您想要的输出类型。
>>> d = '20160105'
>>> t = '013640'
>>> d+t
'20160105013640'
>>> '{}{}'.format(d, t)
'20160105013640'
>>> hundreds = 2
>>> fifties = 1
>>> twenties = 1
>>> tens = 1
>>> fives = 1
>>> ones = 1
>>> quarters = 2
>>> dimes = 1
>>> nickels = 1
>>> pennies = 1
>>> 'I have ' + str(hundreds) + ' hundreds, ' + str(fifties) + ' fifties, ' + str(twenties) + ' twenties, ' + str(tens) + ' tens, ' + str(fives) + ' fives, ' + str(ones) + ' ones, ' + str(quarters) + ' quarters, ' + str(dimes) + ' dimes, ' + str(nickels) + ' nickels, and ' + str(pennies) + ' pennies.'
'I have 2 hundreds, 1 fifties, 1 twenties, 1 tens, 1 fives, 1 ones, 2 quarters, 1 dimes, 1 nickels, and 1 pennies.'
>>> 'I have {} hundreds, {} fifties, {} twenties, {} tens, {} fives, {} ones, {} quarters, {} dimes, {} nickels, and {} pennies.'.format(hundreds, fifties, twenties, tens, fives, ones, quarters, dimes, nickels, pennies)
'I have 2 hundreds, 1 fifties, 1 twenties, 1 tens, 1 fives, 1 ones, 2 quarters, 1 dimes, 1 nickels, and 1 pennies.'
>>> f'I have {hundreds} hundreds, {fifties} fifties, {twenties} twenties, {tens} tens, {fives} fives, {ones} ones, {quarters} quarters, {dimes} dimes, {nickels} nickels, and {pennies} pennies.'
'I have 2 hundreds, 1 fifties, 1 twenties, 1 tens, 1 fives, 1 ones, 2 quarters, 1 dimes, 1 nickels, and 1 pennies.'
Run Code Online (Sandbox Code Playgroud)
毫无错误地创建大格式字符串比进行大量连接要容易得多。再加上格式字符串可以处理实际的格式(例如对齐或舍入),您很快就会只为最简单的情况保留串联,如上所示。