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

标签 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-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')

关于python - 在 Python3 中使用 %x 格式化不好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55697703/

相关文章:

python - 如何在Python中显示百分比和进度条?

python - python/django 中的每小时日志轮转

python - 用于 AJAX 内容的 Scrapy CrawlSpider

django - 如何从覆盖范围中排除文件?

python - 执行 itertools.product 允许不同迭代次数的重复

python - f 字符串表达式中出现类型错误 - 'str' 对象不可调用

python将列中的字符串重命名为指定字符串

python - 如何使用 Python 在 map 上绘制可视化线串?

python - 从首字母为小写的数据框中删除行

python f'string 在 pd.Series.map 函数中不起作用