printf怎么输出字符
格式化输出函数的使用和格式
在Python中,`format()`函数是一个非常有用的工具,用于格式化字符串。这个函数允许你插入和格式化变量值到字符串中。
基本的使用方法如下:
```python
name = "张三"
age = 25
formatted_string = "我的名字是{},我{}岁了。".format(name, age)
print(formatted_string)
```
在这个例子中,`{}`是占位符,`.format()`函数用于将`name`和`age`变量的值插入到占位符的
位置。运行这个代码后,会输出:
```csharp
我的名字是张三,我25岁了。
```
你还可以使用更复杂的格式化选项,例如:
指定宽度和对齐方式:
```python
num = 12345
formatted_string = "{:>10}".format(num)  右对齐,总宽度为10
print(formatted_string)
```
输出:
```vbnet
    12345
```
指定精度和小数位数:
```python
num =
formatted_string = "{:.2f}".format(num)  保留两位小数
print(formatted_string)
```
输出:
```makefile
```
使用复数字符串和列表:
```python
words = ["Hello", "world"]
formatted_string = "{:<10} {:<10}".format(words)  使用解包运算符  将列表中的元素解包为单独的参数
print(formatted_string)
```
输出:
```makefile
Hello    world      注意,这里使用了制表符(tab)进行对齐,所以两个单词之间有一个tab的距离。
```