在 python 中格式化文本,对齐

Formating text in python, alignment

这是代码,它使用 binance API 它遍历所有货币,只显示余额高于 0 的货币:

import time
time.sleep(1)
from datetime import datetime
current_time = datetime.now().strftime("%H:%M:%S")
print(f"\n [{current_time}] Using PYPY3 \n")
print(f" [{current_time}] Importing modules... ")
import os



from binance.client import Client
from forex_python.converter import CurrencyRates
current_time = datetime.now().strftime("%H:%M:%S")
print(f" [{current_time}] Imported the modules!")

api_key = <api_key>
api_secret = <api_password>
client = Client(api_key, api_secret)


def get_balance():
    assets_btc = []
    assets_value = []
    assets = []
    sum_btc = 0.0
    current_btc_price_USD = client.get_symbol_ticker(symbol="BTCUSDT")["price"]
    balances = client.get_account()
    for _balance in balances["balances"]:
        asset = _balance["asset"]
        if _balance["asset"] not in Xcrypto:
            if float(_balance["free"]) != 0.0 or float(_balance["locked"]) != 0.0:
                try:
                    btc_quantity = float(_balance["free"]) + float(_balance["locked"])
                    if asset == "BTC":
                        assets.append(_balance["asset"])
                        sum_btc += btc_quantity
                        assets_value.append(btc_quantity)
                        assets_btc.append(btc_quantity * float(current_btc_price_USD))
                    else:
                        assets.append(_balance["asset"])
                        _price = client.get_symbol_ticker(symbol=asset + "BTC")
                        sum_btc += btc_quantity * float(_price["price"])
                        assets_value.append(btc_quantity)
                        assets_btc.append(btc_quantity * float(_price["price"]) * float(current_btc_price_USD))
                except Exception:
                    pass
    own_usd = sum_btc * float(current_btc_price_USD)
    return float("%.2f" % own_usd), assets, assets_value, assets_btc


if __name__ == "__main__":
    Xcrypto = ["EGLD"]
    current_time = datetime.now().strftime("%H:%M:%S")
    print(f"\n [{current_time}] Starting... \n")
    print(f" [{current_time}] Forbiden cryptos: {Xcrypto} \n")
    current_time = datetime.now().strftime("%H:%M:%S")
    print(f" [{current_time}] Connecting to binance API...")
    get_balance()
    current_time = datetime.now().strftime("%H:%M:%S")
    print(f" [{current_time}] Connected to the binance API! \n")
    current_time = datetime.now().strftime("%H:%M:%S")
    print(f" [{current_time}] Connecting to forex API...")
    USD_RON = float(CurrencyRates().get_rate('USD', 'RON'))
    current_time = datetime.now().strftime("%H:%M:%S")
    print(f" [{current_time}] Connected to the forex API! \n")
    print(f" [{current_time}] Conversion: USD to RON: {'%.2f' % USD_RON} \n")
    current_time = datetime.now().strftime("%H:%M:%S")
    print(f" [{current_time}] Console will be cleared, updating the price every 2 seconds!")
    while 1:
        print("\n")
        Binance_USD, assets, assets_value, assets_btc = get_balance()
        Binance_RON = float("%.2f" % (Binance_USD * USD_RON))
        current_time = datetime.now().strftime("%H:%M:%S")
        os.system('cls' if os.name == 'nt' else 'clear')
        for asset, asset_value, asset_btc in zip(assets, assets_value, assets_btc):
            print(f" [{current_time}] {asset} Balance: {'%.2f' % asset_value} Value: {'%.2f' % (float(asset_btc) * USD_RON)} RON")
        print(f"\n [{current_time}] Total balance:", str(Binance_RON) + " RON\n")

输出:

 [15:11:26] BTC Balance: x.xx, Value: xxxx.xx RON
 [15:11:26] USDT Balance: xxx.xx, Value: xx.xx RON
 [15:11:26] TRX Balance: xx.x, Value: xx.x RON
 [15:11:26] XRP Balance: xxx.x, Value: xxx.xx RON
 [15:11:26] XLM Balance: x.xx, Value: x.xx RON

寻找这样的东西,最长值后刚好 2 个空格:

 [15:11:26] BTC  Balance: x.xx    Value: xxxx.xx  RON
 [15:11:26] USDT Balance: xxx.xx  Value: xx.xx    RON
 [15:11:26] TRX  Balance: xx.xx   Value: xx.xx    RON
 [15:11:26] XRP  Balance: xxx.xx  Value: xxx.xx   RON
 [15:11:26] XLM  Balance: x.xx    Value: x.xxx    RON

此外,任何类型的格式(如 BOLD)都会有所帮助! 使用 windows 命令行 运行 它“python main.py”。 提前致谢!

我假设您的值与代码中的一样。

代码:

import datetime as dt


# ANSI colors
colors = (
    "3[0m",   # End of color
    "3[1m",   # Bold
    "3[4m",   # Underline
)


current_time = dt.datetime.now().time().strftime('%H:%M:%S')
assets = ['BTC', 'USDT', 'TRX', 'XRP', 'XLM']
assets_value = [1.25456, 123.34565, 25.2455, 1234.44655, 456.64565]
assets_btc = [4.24565, 321.345645, 45.2455, 3456.44565, 789.6465]

# get max length
asset_max_len = max(len(i) for i in assets)
balance_max_len = max(len(str(round(i, 2))) for i in assets_value)
value_max_len = max(len(str(round(i, 2))) for i in assets_btc)

for asset, asset_value, asset_btc in zip(assets, assets_value, assets_btc):
    print(f" [{current_time}] {colors[1]}{asset:{asset_max_len}}{colors[0]} {colors[1]}Balance:{colors[0]} {'%.2f' % asset_value:{balance_max_len}} {colors[1]}Value:{colors[0]} {'%.2f' % asset_btc:{value_max_len}} {colors[1]}RON{colors[0]}")

输出: