亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄
1. f-strings (Formatted String Literals) – Python 3.6
2. .format() method
3. % formatting (Old-style)
4. Template strings (for simple cases or user input)
首頁 後端開發(fā) Python教學(xué) 如何在 Python 中格式化字符串

如何在 Python 中格式化字符串

Oct 15, 2025 am 05:47 AM
python 字串格式化

Python提供四種主要字符串格式化方法:f-strings(推薦用於Python 3.6 )、.format()方法(兼容舊版本)、%格式化(舊式,不推薦)和Template字符串(用於安全場(chǎng)景);??其中f-strings因簡潔高效成為現(xiàn)代Python首選方法。

How to format a string in Python

Formatting strings in Python is a common task, and there are several ways to do it depending on your needs and the Python version you're using. Here are the most widely used methods:

1. f-strings (Formatted String Literals) – Python 3.6

This is the most modern and recommended way. You prefix the string with f or F and include variables or expressions inside curly braces {} .

 name = "Alice"
age = 30
greeting = f"Hello, {name}. You are {age} years old."
print(greeting)
# Output: Hello, Alice. You are 30 years old.

You can also include expressions:

 price = 19.99
tax = 0.05
total = f"The total price with tax is ${price * (1 tax):.2f}."
print(total)
# Output: The total price with tax is $20.99.

The :.2f formats the number to two decimal places.

2. .format() method

This method works with older versions of Python and is still widely used. It uses placeholders {} that are replaced by arguments passed to .format() .

 name = "Bob"
age = 25
greeting = "Hello, {}. You are {} years old.".format(name, age)
print(greeting)
# Output: Hello, Bob. You are 25 years old.

You can also use positional or keyword arguments:

 greeting = "Hello, {name}. You are {age} years old.".format(name="Charlie", age=35)
print(greeting)

Or refer by index:

 info = "Name: {0}, Age: {1}, Name again: {0}".format("Dana", 28)
print(info)

3. % formatting (Old-style)

This is the oldest method, similar to C's printf. It uses %s , %d , %f , etc., as placeholders.

 name = "Eve"
age = 22
greeting = "Hello, %s. You are %d years old." % (name, age)
print(greeting)
# Output: Hello, Eve. You are 22 years old.

Common format specifiers:

  • %s – string
  • %d – integer
  • %f – float
  • %.2f – float with 2 decimal places

While it still works, it's generally discouraged in favor of f-strings or .format() .

4. Template strings (for simple cases or user input)

The string.Template class is useful when dealing with user-supplied formatting strings, as it's safer.

 from string import Template

t = Template("Hello, $name. You are $age years old.")
greeting = t.substitute(name="Frank", age=40)
print(greeting)
# Output: Hello, Frank. You are 40 years old.

This method is less common but good for cases where you want to avoid code injection risks in dynamic templates.


Each method has its place:

  • Use f-strings for most modern code – they're fast, readable, and powerful.
  • Use .format() when you need compatibility with older Python versions or more complex formatting logic.
  • Avoid % formatting unless maintaining legacy code.
  • Use Template for user-defined templates where security matters.

Basically, for new projects, go with f-strings unless you have a specific reason not to.

以上是如何在 Python 中格式化字符串的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願(yuàn)投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請(qǐng)聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT

Stock Market GPT

人工智慧支援投資研究,做出更明智的決策

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)程式碼編輯軟體(SublimeText3)

熱門話題

如何從python中的unignts.txt文件安裝包裝 如何從python中的unignts.txt文件安裝包裝 Sep 18, 2025 am 04:24 AM

運(yùn)行pipinstall-rrequirements.txt可安裝依賴包,建議先創(chuàng)建並激活虛擬環(huán)境以避免衝突,確保文件路徑正確且pip已更新,必要時(shí)使用--no-deps或--user等選項(xiàng)調(diào)整安裝行為。

如何用Pytest測(cè)試Python代碼 如何用Pytest測(cè)試Python代碼 Sep 20, 2025 am 12:35 AM

Pytest是Python中簡單強(qiáng)大的測(cè)試工具,安裝後按命名規(guī)則自動(dòng)發(fā)現(xiàn)測(cè)試文件。編寫以test_開頭的函數(shù)進(jìn)行斷言測(cè)試,使用@pytest.fixture創(chuàng)建可複用的測(cè)試數(shù)據(jù),通過pytest.raises驗(yàn)證異常,支持運(yùn)行指定測(cè)試和多種命令行選項(xiàng),提升測(cè)試效率。

如何處理python中的命令行參數(shù) 如何處理python中的命令行參數(shù) Sep 21, 2025 am 03:49 AM

theargparsemodulestherecommondedwaywaytohandlecommand-lineargumentsInpython,提供式刺激,typeValidation,helpmessages anderrornhandling; useSudys.argvforsimplecasesRequeRequeRingminimalSetup。

什麼是BIP?為什麼它們對(duì)比特幣的未來如此重要? 什麼是BIP?為什麼它們對(duì)比特幣的未來如此重要? Sep 24, 2025 pm 01:51 PM

目錄什麼是比特幣改進(jìn)提案(BIP)?為什麼BIP如此重要?比特幣改進(jìn)提案(BIP)的歷史BIP流程如何運(yùn)作? BIP類型什麼是信號(hào)以及礦工如何發(fā)出信號(hào)? Taproot快速試用BIP的利與弊結(jié)語?自2011年以來,對(duì)比特幣的任何改進(jìn)都通過稱為比特幣改進(jìn)提案或??“BIP”的系統(tǒng)進(jìn)行。比特幣改進(jìn)提案(BIP)為比特幣如何發(fā)展提供了指導(dǎo)方針一般來說,BIP有三種可能的類型,其中兩種與比特幣的技術(shù)變革有關(guān)每個(gè)BIP都是從比特幣開發(fā)者之間的非正式討論開始的,他們可以在任何地方聚集,包括Twi

從新手到專家:10個(gè)必備的免費(fèi)公共數(shù)據(jù)集網(wǎng)站 從新手到專家:10個(gè)必備的免費(fèi)公共數(shù)據(jù)集網(wǎng)站 Sep 15, 2025 pm 03:51 PM

對(duì)於數(shù)據(jù)科學(xué)的初學(xué)者而言,從“毫無經(jīng)驗(yàn)”到“行業(yè)專家”的躍遷之路,其核心就是不斷地實(shí)踐。而實(shí)踐的基礎(chǔ),正是豐富多樣的數(shù)據(jù)集。幸運(yùn)的是,網(wǎng)絡(luò)上有大量提供免費(fèi)公共數(shù)據(jù)集的網(wǎng)站,它們是提陞技能、磨練技術(shù)的寶貴資源。

如何使用Python中的@ContextManager Decorator創(chuàng)建上下文管理器? 如何使用Python中的@ContextManager Decorator創(chuàng)建上下文管理器? Sep 20, 2025 am 04:50 AM

Import@contextmanagerfromcontextlibanddefineageneratorfunctionthatyieldsexactlyonce,wherecodebeforeyieldactsasenterandcodeafteryield(preferablyinfinally)actsas__exit__.2.Usethefunctioninawithstatement,wheretheyieldedvalueisaccessibleviaas,andthesetup

如何編寫Python中日常任務(wù)的自動(dòng)化腳本 如何編寫Python中日常任務(wù)的自動(dòng)化腳本 Sep 21, 2025 am 04:45 AM

Identifyrepetitivetasksworthautomating,suchasorganizingfilesorsendingemails,focusingonthosethatoccurfrequentlyandtakesignificanttime.2.UseappropriatePythonlibrarieslikeos,shutil,glob,smtplib,requests,BeautifulSoup,andseleniumforfileoperations,email,w

電腦怎麼選才適合大數(shù)據(jù)分析?高性能計(jì)算的配置指南 電腦怎麼選才適合大數(shù)據(jù)分析?高性能計(jì)算的配置指南 Sep 15, 2025 pm 01:54 PM

大數(shù)據(jù)分析需側(cè)重多核CPU、大容量內(nèi)存及分層存儲(chǔ)。首選多核處理器如AMDEPYC或RyzenThreadripper,兼顧核心數(shù)量與單核性能;內(nèi)存建議64GB起步,優(yōu)先選用ECC內(nèi)存保障數(shù)據(jù)完整性;存儲(chǔ)采用NVMeSSD(系統(tǒng)與熱數(shù)據(jù))、SATASSD(常用數(shù)據(jù))和HDD(冷數(shù)據(jù))組合,提升整體處理效率。

See all articles