![](/img/trans.png)
[英]How to access to the length of the dynamic string, sent as the print argument within the same print method?
[英]Print string in always the same position even if prefix-string has dynamic length
我有一个动态长度(S1)的字符串,我想打印它,我想在它后面添加另一个字符串(S2)。 S2 应始终以给定的长度开始。 就我而言,在 21 个字符之后。 S1 有多长应该无关紧要。
鉴于此代码:
servers = [{"ip": "62.112.10.156", "port": "8150"},
{"ip": "51.15.226.30", "port": "8150"},
{"ip": "188.165.209.184", "port": "8150"}]
for server in servers:
ip = server['ip']
ip = f"IP: {ip}{(' ' * (16 - len(ip)))}"
port = f"Port: {server['port']}"
print(f"{ip} {port}")
这是我得到的:
IP: 62.110.10.136 Port: 8650
IP: 55.15.126.30 Port: 8250
IP: 187.162.209.183 Port: 8030
代码做了我需要的,但它很丑,我想知道一种更pythonic的方法来做到这一点。
servers = [{"ip": "62.112.10.156", "port": "8150"},
{"ip": "51.15.226.30", "port": "8150"},
{"ip": "188.165.209.184", "port": "8150"}]
for server in servers:
ip, port = server['ip'], server['port']
print( f"IP: {ip: <16} Port: {port}")
产出
IP: 62.112.10.156 Port: 8150
IP: 51.15.226.30 Port: 8150
IP: 188.165.209.184 Port: 8150
在这里我做了两件事,我使用 f-string 来执行固定宽度的格式化,并将 ip 和 port 值分配给一行中的变量。 我更喜欢访问 f-string 中的字典,因为它使 f-string 更易于阅读。
使用对齐和宽度字段,请参阅格式字符串语法
for server in servers:
print ( f"IP: {server['ip']:<16}Port: {server['port']}" )
好吧,您想要做的似乎是将字符串填充为 21 个字符,然后附加另一个字符串。 实际上,'IP:' 占用 4 个字符,因此您需要将 'ip' 填充为 17 个字符:
servers = [{"ip": "62.112.10.156", "port": "8150"},
{"ip": "51.15.226.30", "port": "8150"},
{"ip": "188.165.209.184", "port": "8150"}]
for server in servers:
ip = server['ip']
ip = f"IP: {ip.ljust(17)}"
port = f"Port: {server['port']}"
print(f"{ip} {port}")
你可以试试:
for server in servers:
print('IP:', server['ip'].ljust(16), 'PORT:', server['port'])
结果:
IP: 62.112.10.156 PORT: 8150
IP: 51.15.226.30 PORT: 8150
IP: 188.165.209.184 PORT: 8150
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.