在Python3中使用%x格式是否不好?

时间:2019-04-15 21:50:12

标签: python python-3.x f-string

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

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字符串则更容易。这是不好的做法吗?

1 个答案:

答案 0 :(得分:2)

注意:这似乎是一个非常主要的基于意见的问题。我将根据在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')