python print format函數(shù)的格式化輸出技巧有哪些

小樊
87
2024-08-10 01:36:37

  1. 使用占位符進(jìn)行格式化輸出:
name = 'Alice'
age = 25
print('My name is %s and I am %d years old.' % (name, age))
  1. 使用format方法進(jìn)行格式化輸出:
name = 'Bob'
age = 30
print('My name is {} and I am {} years old.'.format(name, age))
  1. 使用f-string進(jìn)行格式化輸出(Python 3.6及以上版本):
name = 'Charlie'
age = 35
print(f'My name is {name} and I am {age} years old.')
  1. 控制輸出格式:
value = 3.14159
print('The value is {:.2f}'.format(value))  # 輸出保留兩位小數(shù)
  1. 使用位置參數(shù)和關(guān)鍵字參數(shù):
name = 'David'
age = 40
print('My name is {0} and I am {1} years old. {0} is a {job}.'.format(name, age, job='teacher'))

0