python - 在 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 用于其他事情。这是不好的做法吗?
解决方案
注意:这似乎是一个非常主要基于意见的问题。我将根据我在 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')
推荐阅读
- java - 如何使用 Map 在 Java 中创建递归树状数据结构
? - python - django rest框架中的JWT身份验证
- python - 如何使用 splinter 在表格中查找网格?
- oracle - 是否可以在不使用 rownum 的情况下一次读取一个 ID?(甲骨文优化)
- swift - 将函数存储在变量中 Telegram 源代码
- java - 创建 ParseObject 时出现 java android i/o 失败异常
- angular - Typescript 中的按位运算
- vue.js - [VUE-CHARTJS]在使用 vuex 和 reactiveProps mixin 时找不到如何使用渐变的示例(API 数据)
- c# - 在运行时更改图形 API (Unity)
- angular - 仅当我手动刷新页面时模型才会打开