首页 > 解决方案 > 在 Python3 中使用 %x 格式是不是很糟糕?

问题描述

有人告诉我让我的字符串格式保持一致。我经常写这样的代码

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 用于其他事情。这是不好的做法吗?

标签: pythonpython-3.xf-string

解决方案


注意:这似乎是一个非常主要基于意见的问题。我将根据我在 Python 社区中看到的情况提供答案。

%用于格式化字符串也不错。一些开发人员建议使用 f 字符串,str.format()因为这样做可以提高可读性。通常,开发人员建议使用 f 字符串。在较低版本的 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')

推荐阅读