Python 字串長度查詢(三種方法)


字串是 Python 中的一種資料型別,它是由一系列 Unicode 字元組成。一旦宣告,它就是不可變的。在這篇文章中,我們將學習查詢字串長度的不同方法。

使用 len() 函式

這是最直接的方法。這裡我們使用一個名為 len() 的庫函式。字串作為引數傳遞給函式,我們得到字串中字元的數量。

示例

str ="Tutorials"
print("Length of the String is:", len(str))

輸出

執行以上程式碼將得到以下結果:

Length of the String is: 9

使用切片

我們可以使用字串切片的方法來計算字串中每個字元的位置。字串中位置的最終計數就成為字串的長度。

示例

str = "Tutorials"
position = 0
# Stop when all the positions are counted
while str[position:]:
   position += 1
# Print the total number of positions
print("The total number of characters in the string: ",position)

輸出

執行以上程式碼將得到以下結果:

The total number of characters in the string: 9

使用 join() 和 count() 函式

join() 和 count() 字串函式也可以使用。

示例

str = "Tutorials"
#iterate through each character of the string
# and count them
length=((str).join(str)).count(str) + 1
# Print the total number of positions
print("The total number of characters in the string: ",length)

輸出

執行以上程式碼將得到以下結果:

The total number of characters in the string: 9

更新於:2019年8月7日

2K+ 閱讀量

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.