中使用字符串格式而不是字符串连接是否更

中使用字符串格式而不是字符串连接是否更

本文介绍了在 Python 3 中使用字符串格式而不是字符串连接是否更 Pythonic?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在用 Python 3.4 编写一个文本游戏,它需要经常使用 print() 函数来向用户显示变量.

So I'm programming a text game in Python 3.4 that requires the use of the print() function very often to display variables to the user.

我一直采用的两种方法是字符串格式字符串连接:

The two ways I've always done this is with string formatting and string concatenation:

print('{} has {} health left.'.format(player, health))

还有,

print(player + ' has ' + str(health) + ' health left.')

那么哪个更好?它们同样具有可读性和快速输入性,并且执行完全相同.哪个更Pythonic,为什么?

So which is better? They're both equally as readable and quick to type, and perform exactly the same. Which one is more Pythonic and why?

问题是因为我在 Stack Overflow 上找不到与 Java 无关的答案.

Question asked as I couldn't find an answer for this on Stack Overflow that wasn't concerned with Java.

推荐答案

取决于字符串的长度和变量的数量.对于您的用例,我相信 string.format 更好,因为它具有更好的性能并且看起来更清晰易读.

Depends upon how long your string is and how many variables. For your use case I believe string.format is better as it has a better performance and looks cleaner to read.

有时对于更长的字符串 + 看起来更干净,因为变量的位置被保留在它们应该在字符串中的位置,你不必四处移动你的眼睛来映射 {} 到相应的变量.

Sometimes for longer strings + looks cleaner because the position of the variables are preserved where they should be in the string and you don't have to move your eyes around to map the position of {} to the corresponding variable.

如果您可以设法升级到 Python 3.6,您可以使用更新的更直观的字符串格式语法,如下所示,并两全其美:

If you can manage to upgrade to Python 3.6 you can use the newer more intuitive string formatting syntax like below and have best of both worlds:

player = 'Arbiter'
health = 100
print(f'{player} has {health} health left.')

如果你有一个非常大的字符串,我建议使用像 Jinja2 (http://jinja.pocoo.org/docs/dev/) 或类似的东西.

If you have a very large string, I recommend to use a template engine like Jinja2 (http://jinja.pocoo.org/docs/dev/) or something along the line.

参考:https://www.python.org/dev/peps/pep-0498/

这篇关于在 Python 3 中使用字符串格式而不是字符串连接是否更 Pythonic?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 23:10