python print中的format怎么使用

其他教程   发布日期:2024年04月17日   浏览次数:438

这篇文章主要介绍了python print中的format怎么使用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇python print中的format怎么使用文章都会有所收获,下面我们一起来看看吧。

变量插入字符串的方法

Python中的format()函数是一种将变量插入字符串的方法,能够使字符串更易于阅读和理解。它支持许多不同的用法,以下是具体的用法和说明:

  • 使用位置参数传递变量

  1. name = 'John'
  2. age = 25
  3. print('My name is {}, and I am {} years old.'.format(name, age))
  4. # 输出:My name is John, and I am 25 years old.
  • 使用索引传递变量

  1. name = 'John'
  2. age = 25
  3. print('My name is {0}, and I am {1} years old.'.format(name, age))
  4. # 输出:My name is John, and I am 25 years old.
  • 使用关键字参数传递变量

  1. name = 'John'
  2. age = 25
  3. print('My name is {n}, and I am {a} years old.'.format(n=name, a=age))
  4. # 输出:My name is John, and I am 25 years old.
  • 格式化数字

  1. price = 19.99
  2. print('The price is ${:.2f}'.format(price))
  3. # 输出:The price is $19.99
  • 对齐文本

  1. text = 'Hello'
  2. print('{:>10}'.format(text)) # 右对齐输出,总宽度为10
  3. # 输出: Hello
  4. print('{:^10}'.format(text)) # 居中输出,总宽度为10
  5. # 输出: Hello
  6. print('{:<10}'.format(text)) # 左对齐输出,总宽度为10
  7. # 输出:Hello
  • 使用格式化字符串(Python 3.6及以上版本)

  1. name = 'John'
  2. age = 25
  3. print(f'My name is {name}, and I am {age} years old.')
  4. # 输出:My name is John, and I am 25 years old.
  • 使用字典传递变量

  1. person = {'name': 'John', 'age': 25}
  2. print('My name is {name}, and I am {age} years old.'.format(**person))
  3. # 输出:My name is John, and I am 25 years old.
  • 使用下标操作符获取列表中的元素

  1. fruits = ['apple', 'banana', 'cherry']
  2. print('My favorite fruit is {0[1]}'.format(fruits))
  3. # 输出:My favorite fruit is banana
  • 使用花括号转义

  1. print('{{Hello}}'.format()) # 输出:{Hello}
  • 使用冒号分隔格式字符串和变量名称,对变量进行进一步格式化

  1. name = 'John'
  2. score = 95
  3. print('Student: {0:&lt;10} Score: {1:.2f}'.format(name, score))
  4. # 输出:Student: John Score: 95.00
  • 根据变量类型自动选择格式

  1. x = 42
  2. y = 3.14
  3. print('x is {!r}, y is {!s}'.format(x, y))
  4. # 输出:x is 42, y is 3.14
  • 使用填充字符

  1. x = 42
  2. print('{:0&gt;5}'.format(x)) # 右对齐,用 0 填充,总宽度为 5
  3. # 输出:00042
  • 根据变量类型选择不同的进制输出

  1. x = 42
  2. print('bin: {0:b}, oct: {0:o}, hex: {0:x}'.format(x))
  3. # 输出:bin: 101010, oct: 52, hex: 2a
  • 自定义格式化函数

  1. def format_salary(salary):
  2. if salary > 10000:
  3. return '{:.1f}K'.format(salary / 1000)
  4. else:
  5. return '${:,.2f}'.format(salary)
  6. print(format_salary(5000)) # $5,000.00
  7. print(format_salary(15000)) # 15.0K
  • 使用 ** 和 * 进行动态参数传递

  1. data = {'name': 'John', 'age': 25}
  2. print('{name} is {age} years old.'.format(**data)) # John is 25 years old.
  3. fruits = ['apple', 'banana', 'cherry']
  4. print('My favorite fruits are {}, {} and {}.'.format(*fruits)) # My favorite fruits are apple, banana and cherry.

以上就是python print中的format怎么使用的详细内容,更多关于python print中的format怎么使用的资料请关注九品源码其它相关文章!