简体   繁体   English

“:”在python中的格式方法中有什么作用?

[英]What does ":" do in the format methods in python?

print("{:2d} file: {:>25}".format(idx + 1, filename_list[idx]) )

This code is from a forloop trying to loop through file names.此代码来自试图循环文件名的 forloop。

The idx variable is the iterator and the filename_list is the list of filenames. idx变量是迭代器, filename_list是文件名列表。

The list is made up of file names like this ie name or names seperated by underscore, number and the file extension该列表由这样的文件名组成,即名称或由下划线、数字和文件扩展名分隔的名称

Boston_Chiwawa_0478.jpg

My question is, what does :2d and :>25 do in this code?我的问题是, :2d:>25在这段代码中做了什么?

Using your example...用你的例子...

{:2d} formats idx + 1 to 2 characters using additional leading padding if required. {:2d}如果需要,使用额外的前导填充来格式化idx + 1到 2 个字符。

{:>25} formats filename_list[idx] to the right hand side with a fixed width of 25 characters. {:>25} filename_list[idx]格式化为右侧,固定宽度为 25 个字符。 If there is less than 25 characters in the file name, leading spaces will be shown.如果文件名少于 25 个字符,将显示前导空格。

Also worth noting, in Python versions 3.6 and above, it can be re-written with a f-string as follows:另外值得注意的是,在 Python 3.6 及以上版本中,它可以用 f-string 重写,如下所示:

print(f"{idx + 1:2d} file: {filename_list[idx]:>25}")

To the left of the colon inside the curly braces is the expression and to the right side of the colon is the formatting string that it applies to it.花括号内冒号的左边是表达式,冒号的右边是它所应用的格式字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM