我想知道是否有一种更好(更短/更干净)的格式以下代码。
# Debug info
print('#-----------------------------------------------------------------#')
print('')
print('Id: {_id}, Name: {_name}'.format(_id = self._id, _name = self._name))
print('')
print(' Attributes:')
print('')
print(' {_attribute}: (level: {_level}), (experience: {_exp})'.format(_attribute = self._attribs[0]._name, _level = self._attribs[0]._level, _exp = self._attribs[0]._exp))
print(' Rebirth: (level: {_level}), (experience: {_exp})'.format(_level = self._attribs[0]._rebirth[0], _exp = self._attribs[0]._rebirth[1]))
print(' Rank: (level: {_level}), (experience: {_exp})'.format(_level = self._attribs[0]._rank[0], _exp = self._attribs[0]._rank[1]))
print(' Tier: (level: {_level}), (experience: {_exp})'.format(_level = self._attribs[0]._tier[0], _exp = self._attribs[0]._tier[1]))
这是output
:
#-----------------------------------------------------------------#
Id: 0, Name: End
Attributes:
Vitality: (level: 1), (experience: 0.0)
Rebirth: (level: 0), (experience: 0.0)
Rank: (level: 0), (experience: 0.0)
Tier: (level: 0), (experience: 0.0)
答案 0 :(得分:0)
您可以采取一些措施来简化这一点。
首先,可以通过在上一个打印语句的末尾添加print('')
来实现'\n'
。
第二,可以使用'\t'
第三,您可以将重复的部分分成for
循环。
# Debug info
print('#-----------------------------------------------------------------#\n')
print('Id: {_id}, Name: {_name}\n'.format(_id=self._id, _name=self._name))
print('\tAttributes:\n')
for a in self.__attribs:
print('\t\t{_name}: (level: {_level}), (experience: {_exp})\n'.format(_name=a._name, _level=a._level, _exp=a._exp))
for t, at in [('Rebirth', a._rebirth), ('Rank', a._rank), ('Tier', a._tier)]:
print('\t\t\t{_title}: (level: {_level}), (experience: {_exp}'.format(_title=t, _level=at[0], _exp=at[1])
如果您使用的是Python 3,则可以利用f字符串进行语法更整洁的格式化。
https://medium.com/@NirantK/best-of-python3-6-f-strings-41f9154983e