Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用.format()排列字符串_Python_String - Fatal编程技术网

Python 使用.format()排列字符串

Python 使用.format()排列字符串,python,string,Python,String,我只需要使用.format()函数将所有列表中的asterix行放在一起。到目前为止,我只能让他们远离同一行的标题。我需要从每个字符串中获取第一个asterix来对齐。对不起,我的问题是noob index = 0 choice_titles = ['Steal:','Deal:','Comp Steal:','Comp Deal:'] choice_counts = [3, 7, 4, 6] print('Game Stats: \n') while index < len(choi

我只需要使用.format()函数将所有列表中的asterix行放在一起。到目前为止,我只能让他们远离同一行的标题。我需要从每个字符串中获取第一个asterix来对齐。对不起,我的问题是noob

index = 0
choice_titles = ['Steal:','Deal:','Comp Steal:','Comp Deal:']
choice_counts = [3, 7, 4, 6]

print('Game Stats: \n')

while index < len(choice_counts):
    (format(choice_titles[index], '<10s'))
    print(choice_titles[index], end='  ' )

    asterix_Disp = ''.join('*' for number in range(0, choice_counts[index]))
    (format(asterix_Disp, '>10s'))
    print(asterix_Disp)

    index += 1
index=0
选择标题=['Steal:','Deal:','Comp Steal:','Comp Deal:']
选项计数=[3,7,4,6]
打印('游戏统计信息:\n')
而指数
为了使标题对齐,您需要确保标题的打印长度相同<代码>'Comp Steal:'的长度为11个字符,所以您的格式至少应该是这样,10个字符不够。至少12点左右

此外,
format()
返回格式化为该规范的字符串。你什么都不用做。我猜你想把它打印出来

print(format(choice_titles[index], '12s'), end='  ')
您不需要格式化星号,因为它们位于末尾。它不会在其他任何事情上偏离对齐。把它打印出来。p、 在美国,要重复一个字符
n
次,只需将该字符乘以
n
。你所拥有的是不必要的复杂

print('*' * choice_counts[index])

这已经奏效了,看起来干净多了!谢谢你,你是一个传奇!您可以添加预期输出的外观吗?