我有一个要打印的具有动态长度(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
代码可以满足我的需求,但是它很丑陋,我想知道一种更Python化的方法。
答案 0 :(得分:1)
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字符串执行固定宽度的格式化,并将ip和port值分配给一行中的变量。我更喜欢在f字符串中访问字典,因为它使f字符串更易于阅读。
答案 1 :(得分:1)
使用对齐和宽度字段,请参见format-string-syntax
for server in servers:
print ( f"IP: {server['ip']:<16}Port: {server['port']}" )
答案 2 :(得分:1)
看来,您想要做的是将字符串填充为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}")
答案 3 :(得分:0)
您可以尝试:
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