有人告诉我要使我的字符串格式保持一致。我经常写这样的代码
print(f'\nUpdate Frame: {update_frame}',
' x-pos: %spx' % round(self.x),
' y-pos: %spx' % round(self.y),
' x-vel: %spx/u' % round(self.vx),
' y-vel: %spx/u' % round(self.vy),
sep='\n')
因为我认为在某些事情上使用 %x
更容易(比如追加单位),但在其他事情上使用 f-strings 更容易。这是不好的做法吗?
注意:这似乎是一个非常主要基于意见的问题。我将根据我在 Python 社区中看到的内容提供答案。
使用 %
来格式化字符串是一个不错的用法。 一些开发人员建议使用 f 字符串和 str.format()
,因为这样做可以提高可读性。一般来说,开发人员推荐使用 f-strings。在较低版本的 python 中,应该使用 str.format()
。
f 弦:
print(f'\n Update Frame: {update_frame}',
f' x-pos: {round(self.x)}px' ,
f' y-pos: {round(self.y)}px',
f' x-vel: {round(self.vx)}px/u',
f' y-vel: {round(self.vy)}px/u',
sep='\n')
str.format():
print('\n Update Frame: {}'.format(update_frame),
' x-pos: {}px'.format(round(self.x)) ,
' y-pos: {}px'.format(round(self.y)),
' x-vel: {}px/u'.format(round(self.vx)),
' y-vel: {}px/u'.format(round(self.vy)),
sep='\n')