简体   繁体   English

Python 中的 format() 实际上是做什么的?

[英]What does format() in Python actually do?

I'm coming into Python3 after spending time with Ruby, R, and some Java.在与 Ruby、R 和一些 Java 相处一段时间后,我开始使用 Python3。 Immediately I've come across the format() function and I'm a little lost as to what it does.我立即遇到了 format() function ,我对它的作用有点迷茫。 I've read Python |我读过Python | format() function and see that it somehow resembles this in ruby: format() function并看到它在某种程度上类似于 ruby:

my_name = "Melanie"
puts "My name is #{my_name}."

Outputs: "My name is Melanie."输出:“我的名字是梅兰妮。”

However, I don't understand why I can't just use a variable as above.但是,我不明白为什么我不能只使用上面的变量。 I must be very much misunderstanding the usage of the format() function.我一定非常误解了 format() function 的用法。 (I'm a novice, please be gentle.) (我是新手,请温柔。)

So what does format() actually do?那么 format() 实际上是做什么的呢?

You can definitely use a variable in the string example that you have shown, in the following manner:您绝对可以通过以下方式在显示的字符串示例中使用变量:

my_name = "Melanie"
Output = "My name is " + my_name + "."
print(Output)

My name is Melanie.

This is the easy way, but not the most elegant.这是最简单的方法,但不是最优雅的。

In the above example, I have used 3 lines and created 2 variables (my_name and Output)在上面的示例中,我使用了 3 行并创建了 2 个变量(my_name 和 Output)

However, I can get the same output using just one line of code and without creating any variables, using format()但是,我可以使用 format() 仅使用一行代码而不创建任何变量来获得相同的 output

print("My name is {}.".format("Melanie"))

My name is Melanie.

Curly braces {} are used as placeholders, and the value we wish to put in the placeholders are passed as parameters into the format function.花括号 {} 用作占位符,我们希望放入占位符的值作为参数传递到格式 function 中。

If you have more than one placeholder in the string, python will replace the placeholders by values, in order.如果字符串中有多个占位符,python 将按顺序将占位符替换为值。

Just make sure that the number of values passed as parameters to format(), is equal to the number of placeholders created in the string.只需确保作为参数传递给 format() 的值的数量等于在字符串中创建的占位符的数量。

For example:例如:

print("My name is {}, and I am {}.".format("Melanie",26))

My name is Melanie, and I am 26.

There are 3 different ways to specify placeholders and their values:有 3 种不同的方式来指定占位符及其值:

Type 1:类型 1:

print("My name is {name}, and I am {age}.".format(name="Melanie", age=26))

Type 2:类型 2:

print("My name is {0}, and I am {1}.".format("Melanie",26))

Type 3:类型 3:

print("My name is {}, and I am {}.".format("Melanie",26))

Additionally, by using format() instead of a variable, you can:此外,通过使用 format() 而不是变量,您可以:

  1. Specify the data type, and指定数据类型,并且
  2. Add a formatting type to format the result.添加格式化类型以格式化结果。

For example:例如:

print("{0:^7} has completed {1:.3f} percent of task {2}".format("Melanie",75.765367,1))

Melanie has completed 75.765 percent of task 1.

I have set the data type for the percentage field to be a float, with 3 decimals, and given a character length of 7 to the name, and center-aligned it.我已将百分比字段的数据类型设置为浮点数,有 3 个小数,名称的字符长度为 7,并使其居中对齐。

The alignment codes are: alignment 代码为:

' < ':left-align text '<':左对齐文本

' ^ ':center text ' ^ ': 居中文本

' > ':right-align ' > ':右对齐

The format() method is helpful when you have multiple substitutions and formattings to perform on a string.当您对字符串执行多个替换和格式化时,format() 方法很有帮助。

An example using the format function is this:使用格式 function 的示例如下:

name =  Arnold
age = 5

print("{ }, { }".format(name, age))

This displays:这显示:

Arnold, 5

The format function is a method for string in python, it is use to add a variable to string. function 格式是 python 中的字符串方法,用于在字符串中添加变量。 for example:例如:

greetings = 'hello {0}'
visitor = input('please enter your name')
print(greetings.format(visitor))

it can also be use to pad/position string also, thisn actually align the visitor into to the greetings in 10 byte of space它也可以用于填充/定位字符串,这实际上将访问者与 10 字节空间中的问候对齐

greetings = 'hello {0:^10}'
visitor = input('please enter your name')
print(greetings.format(visitor))

Also, there are two type of format in python 3x: the format expression and the format function.此外,在 python 3x 中有两种格式:格式表达式和格式 function。 the format expression is actually this '%' and many more on 'format'.格式表达式实际上是这个 '%' 以及更多关于 'format' 的内容。 Maybe you should check on the doc 'format' by typing "help(''.format)"也许你应该通过输入“help(''.format)”来检查文档'format'

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

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