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

2024-06-28 20:24:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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字符串更容易。这种做法不好吗?你知道吗


Tags: 字符串代码posself格式update事情frame
1条回答
网友
1楼 · 发布于 2024-06-28 20:24:48

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

相关问题 更多 >