如何在 Python 中獲取字串的長度?
字串是一組字元,可以用來表示單個單詞或整個短語。在 Python 中,字串易於使用,因為它們不需要顯式宣告,並且可以使用或不使用說明符來定義。
Python 有多種內建函式和方法用於操作和訪問字串。因為 Python 中的一切都是物件,所以字串是 String 類的一個物件,它有幾種方法。
在這篇文章中,我們將討論如何在 Python 中獲取字串的長度。
使用 len() 函式
Python 中的len()函式接受字串作為引數並返回其長度。此函式不僅可以用於字串,還可以用於列表或任何可迭代物件。
示例
在下面給出的程式中,我們正在獲取一個字串作為輸入,並使用 len() 函式找出該字串的長度。
s1 = "Tutorialspoint" length = len(s1) print("The Length of the string",s1,"is",length)
輸出
上述程式的輸出為:
('The Length of the string', 'Tutorialspoint', 'is', 14)
使用切片運算子
我們還可以使用切片運算子計算字串的長度。我們可以使用切片運算子遍歷字串,並在出現字元的每個位置將計數增加一個值。計數的最終值將是字串的長度。
示例
在下面給出的程式中,我們正在使用獲取字串輸入,並且我們正在使用切片運算子獲取一個可迭代變數來遍歷字串並找到字串的長度。
s1 = "Tutorialspoint" i = 0 while s1[i:]: i += 1 print("The length of the string",s1,"is",i)
輸出
上述程式的輸出為:
('The length of the string', 'Tutorialspoint', 'is', 14)
使用 for in 迴圈
我們可以使用迴圈遍歷字串並計算其中的字元數。
示例
以下是一個示例:
s1 = "Tutorialspoint" i = 0 for char in s1: i += 1 print("The length of the string",s1,"is",i)
輸出
上述程式的輸出為:
('The length of the string', 'Tutorialspoint', 'is', 14)
使用 join() 和 count() 方法
join 函式返回一個可迭代物件作為輸出,因此透過使用 count() 方法,我們可以找到結果可迭代物件中的字元數。
示例
在下面給出的示例中,我們使用 join() 和 count() 方法來找出可迭代物件的數目並使用 count() 對其進行計數。
s1 = "Tutorialspoint" length=((s1).join(s1)).count(s1) + 1 print("The length of the string",s1,"is",length)
輸出
上述程式的輸出為:
('The length of the string', 'Tutorialspoint', 'is', 14)
廣告