搜尋
首頁後端開發Python教學Python程式範例,示範字串插值

Python程式範例,示範字串插值

Sep 19, 2023 am 10:53 AM
python範例字串插值

Python程式範例,示範字串插值

在Python中,我們可以使用f-string、%運算子和format()方法來示範字串插值。字串插值是將動態資料或變數插入字串的過程。當使用變數或表達式形成字串時,它非常有用,而無需使用任何字串格式化或字串連接。在本文中,我們將看到如何使用Python進行字串插值。

Method 1 : Using f-string

一個f-string是一個以f F開頭的字串字面值。前綴f或F表示該字串是一個f-string。字串中包含用花括號{}括起來的表達式。這些表達式可以具有在運行時評估的動態值。

Example

In the below example, we create three variables namely name, age, and height whose values are initialized. A message is created using an f-string in which name, age, and height 是The value of these expressions is taken from the variables(name, age, and height) at runtime.

name = 'John'
age = 25
height = 1.75

message = f"My name is {name}. I am {age} years old and {height} meters tall."
print(message)

輸出

My name is John. I am 25 years old and 1.75 meters tall.

Method 2 : Using the format() method

The format() method is used to do string interpolation by inserting values in a string using placeholders. These placeholders are represented in the string using curly braces {}. The values at the place the string using curly braces {}. The values at the place placeue. () attribute at the end of the string.

Example

In the below example, we first initialize three variables namely name, age, and height. We then create a message using a string with placeholders in it represented by curly braces{}.The formaties odue.The fors value specs specus specus specus fors specjue. placeholders.

name = 'John'
age = 25
height = 1.75

message = "My name is {}. I am {} years old and {} meters tall.".format(name, age, height)
print(message)

輸出

My name is John. I am 25 years old and 1.75 meters tall.

Method 3 : Using the % operator

The % operator works similarly to the use of % operators in printf() function in C-programming. The string contains expressions in the form of %s,%d,%f, etc which specify the type of value for example %s specifies string,%d specifies integer,%f specifies float value, etc.

Example

在下面的範例中,我們初始化了三個變量,分別是name、age和height,然後使用%運算子建立了一個訊息字串。字串包含了以佔位符形式指定的表達式,這些表達式使用%s、%d和%f來表示。這些佔位符的值是透過元組傳遞給%運算子的。

name = 'John'
age = 25
height = 1.75

message = "My name is %s. I am %d years old and %.2f meters tall." % (name, age, height)
print(message)

輸出

My name is John. I am 25 years old and 1.75 meters tall.

結論

字串插值可讓您建立一個包含變數和表達式的字串。這些表達式或變數的值是動態的,並在運行時取得。 Python提供了像f-string、format方法和%運算元這樣的方法來建立字串插值。在本文中,我們透過範例了解了所有三種方法。

以上是Python程式範例,示範字串插值的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:tutorialspoint。如有侵權,請聯絡admin@php.cn刪除
Python腳本可能無法在UNIX上執行的一些常見原因是什麼?Python腳本可能無法在UNIX上執行的一些常見原因是什麼?Apr 28, 2025 am 12:18 AM

Python腳本在Unix系統上無法運行的原因包括:1)權限不足,使用chmod xyour_script.py賦予執行權限;2)Shebang行錯誤或缺失,應使用#!/usr/bin/envpython;3)環境變量設置不當,可打印os.environ調試;4)使用錯誤的Python版本,可在Shebang行或命令行指定版本;5)依賴問題,使用虛擬環境隔離依賴;6)語法錯誤,使用python-mpy_compileyour_script.py檢測。

舉一個場景的示例,其中使用Python數組比使用列表更合適。舉一個場景的示例,其中使用Python數組比使用列表更合適。Apr 28, 2025 am 12:15 AM

使用Python數組比列表更適合處理大量數值數據。 1)數組更節省內存,2)數組對數值運算更快,3)數組強制類型一致性,4)數組與C語言數組兼容,但在靈活性和便捷性上不如列表。

在Python中使用列表與數組的性能含義是什麼?在Python中使用列表與數組的性能含義是什麼?Apr 28, 2025 am 12:10 AM

列表列表更好的forflexibility andmixDatatatypes,何時出色的Sumerical Computitation sand larged數據集。 1)不可使用的列表xbilese xibility xibility xibility xibility xibility xibility xibility xibility xibility xibility xibles and comply offrequent elementChanges.2)

Numpy如何處理大型數組的內存管理?Numpy如何處理大型數組的內存管理?Apr 28, 2025 am 12:07 AM

numpymanagesmemoryforlargearraysefefticefticefipedlyuseviews,副本和內存模擬文件.1)viewsAllowSinglicingWithOutCopying,直接modifytheoriginalArray.2)copiesCanbecopy canbecreatedwitheDedwithTheceDwithThecevithThece()methodervingdata.3)metservingdata.3)memore memore-mappingfileShessandAstaStaStstbassbassbassbassbassbassbassbassbassbassbb

哪個需要導入模塊:列表或數組?哪個需要導入模塊:列表或數組?Apr 28, 2025 am 12:06 AM

Listsinpythondonotrequireimportingamodule,helilearraysfomthearraymoduledoneedanimport.1)列表列表,列表,多功能和canholdMixedDatatatepes.2)arraysaremoremoremoremoremoremoremoremoremoremoremoremoremoremoremoremoremeremeremeremericdatabuteffeftlessdatabutlessdatabutlessfiblesible suriplyElsilesteletselementEltecteSemeTemeSemeSemeSemeTypysemeTypysemeTysemeTypysemeTypepe。

可以在Python數組中存儲哪些數據類型?可以在Python數組中存儲哪些數據類型?Apr 27, 2025 am 12:11 AM

pythonlistscanStoryDatatepe,ArrayModulearRaysStoreOneType,and numpyArraySareSareAraysareSareAraysareSareComputations.1)列出sareversArversAtileButlessMemory-Felide.2)arraymoduleareareMogeMogeNareSaremogeNormogeNoreSoustAta.3)

如果您嘗試將錯誤的數據類型的值存儲在Python數組中,該怎麼辦?如果您嘗試將錯誤的數據類型的值存儲在Python數組中,該怎麼辦?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Python標準庫的哪一部分是:列表或數組?Python標準庫的哪一部分是:列表或數組?Apr 27, 2025 am 12:03 AM

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器