python format()例题
Python中的format()函数是一种非常强大和灵活的字符串格式化工具。它允许我们将值插入到字符串中,并选择如何展示这些值。
格式化字符串在很多情况下都非常有用,例如,当我们需要将变量的值插入到日志消息、错误消息或用户界面中时,通过使用format()函数可以使这些消息具有可读性和易于理解。
format()函数的基本语法如下:
```
formatted_string = "Text with {} and {}".format(value1, value2)
```
在这个例子中,我们用`{}`作为占位符,然后通过.format()方法来指定占位符的值。
让我们通过一些例子来说明format()函数的使用。
### 1.简单的格式化
格式化字符串的最简单用法是在字符串中插入变量的值。例如:
```python
字符串函数pythonname = "Alice"
age = 25
print("My name is {} and I'm {} years old.".format(name, age))
```
输出:
```
My name is Alice and I'm 25 years old.
```
在这个例子中,我们创建了一个字符串,其中包含两个占位符`{}`。然后,通过调用.format()方法来指定这两个占位符的值。
### 2.通过位置指定占位符的值
我们还可以通过指定占位符的位置来格式化字符串。例如:
```python
name = "Alice"
age = 25
print("My name is {0} and I'm {1} years old. {0} is my favorite name.".format(name, age))
```
输出:
```
My name is Alice and I'm 25 years old. Alice is my favorite name.
```
在这个例子中,我们在占位符的大括号中添加了索引号(从0开始)。索引号指定了占位符对应的位置。
### 3.通过关键字指定占位符的值
除了通过位置来指定占位符的值,我们还可以通过关键字来指定。例如:
```python
name = "Alice"
age = 25
print("My name is {name} and I'm {age} years old. {name} is my favorite name.".format(name=name, age=age))
```
输出:
```
My name is Alice and I'm 25 years old. Alice is my favorite name.
```
在这个例子中,我们在.format()方法中使用了`name=name`和`age=age`的形式。这样,我们可以通过关键字来指定占位符的值。
### 4.格式化数字
format()函数还可以用于格式化数字的显示方式。例如:
```python
x = 1000
y = 3.14159
print("The value of x is {:,} and the value of y is {:.2f}".format(x, y))
```
输出:
```
The value of x is 1,000 and the value of y is 3.14
```
在这个例子中,`:,`表示要将数值使用千位分隔符进行格式化。而`:.2f`表示要将数值保留两位小数。
### 5.指定对齐方式
我们还可以通过在占位符中添加对齐方式来格式化字符串。例如:
```python
x = 100
y = 3
print("x: {:>5} y: {:<5}".format(x, y))
```
输出:
```
x: 100 y: 3
```
在这个例子中,`>`表示右对齐,`<`表示左对齐。数字5表示要占用的字符数。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论