溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python print中的format怎么使用

發(fā)布時間:2023-03-25 14:42:09 來源:億速云 閱讀:137 作者:iii 欄目:開發(fā)技術

這篇文章主要介紹了python print中的format怎么使用的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇python print中的format怎么使用文章都會有所收獲,下面我們一起來看看吧。

變量插入字符串的方法

Python中的format()函數(shù)是一種將變量插入字符串的方法,能夠使字符串更易于閱讀和理解。它支持許多不同的用法,以下是具體的用法和說明:

  • 使用位置參數(shù)傳遞變量

name = 'John'
age = 25
print('My name is {}, and I am {} years old.'.format(name, age))
# 輸出:My name is John, and I am 25 years old.
  • 使用索引傳遞變量

name = 'John'
age = 25
print('My name is {0}, and I am {1} years old.'.format(name, age))
# 輸出:My name is John, and I am 25 years old.
  • 使用關鍵字參數(shù)傳遞變量

name = 'John'
age = 25
print('My name is {n}, and I am {a} years old.'.format(n=name, a=age))
# 輸出:My name is John, and I am 25 years old.
  • 格式化數(shù)字

price = 19.99
print('The price is ${:.2f}'.format(price))
# 輸出:The price is $19.99
  • 對齊文本

text = 'Hello'
print('{:>10}'.format(text))  # 右對齊輸出,總寬度為10
# 輸出:     Hello
print('{:^10}'.format(text))  # 居中輸出,總寬度為10
# 輸出:  Hello   
print('{:<10}'.format(text))  # 左對齊輸出,總寬度為10
# 輸出:Hello
  • 使用格式化字符串(Python 3.6及以上版本)

name = 'John'
age = 25
print(f'My name is {name}, and I am {age} years old.')
# 輸出:My name is John, and I am 25 years old.
  • 使用字典傳遞變量

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

fruits = ['apple', 'banana', 'cherry']
print('My favorite fruit is {0[1]}'.format(fruits))
# 輸出:My favorite fruit is banana
  • 使用花括號轉義

print('{{Hello}}'.format())  # 輸出:{Hello}
  • 使用冒號分隔格式字符串和變量名稱,對變量進行進一步格式化

name = 'John'
score = 95
print('Student: {0:&lt;10} Score: {1:.2f}'.format(name, score))
# 輸出:Student: John       Score: 95.00
  • 根據(jù)變量類型自動選擇格式

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

x = 42
print('{:0&gt;5}'.format(x))  # 右對齊,用 0 填充,總寬度為 5
# 輸出:00042
  • 根據(jù)變量類型選擇不同的進制輸出

x = 42
print('bin: {0:b}, oct: {0:o}, hex: {0:x}'.format(x))
# 輸出:bin: 101010, oct: 52, hex: 2a
  • 自定義格式化函數(shù)

def format_salary(salary):
    if salary > 10000:
        return '{:.1f}K'.format(salary / 1000)
    else:
        return '${:,.2f}'.format(salary)
print(format_salary(5000))   # $5,000.00
print(format_salary(15000))  # 15.0K
  • 使用 ** 和 * 進行動態(tài)參數(shù)傳遞

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

關于“python print中的format怎么使用”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“python print中的format怎么使用”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI