Python 字串 len() 方法



Python 字串len()方法用於獲取字串的長度。字串是字元的集合,字串的長度是其中字元(Unicode 值)的數量。

len() 方法確定字串中包含多少個字元,包括標點符號、空格和所有型別的特殊字元。它不會計算儲存在物件中的元素數量,因此此方法有助於提供元素的數量。

例如,字串“Tutorials Point”包含 15 個字元,包括空格。

語法

以下是 Python 字串 len() 方法的語法

len(str)

引數

此方法不接受任何引數。

返回值

此方法返回字串的長度。

示例

在下面的示例中,我們使用 Python 字串 len() 方法查詢給定字串“this is string example....wow!!!”的長度

str = "this is string example....wow!!!";
print "Length of the string: ", len(str)

以上程式碼的輸出如下

Length of the string:  32

示例

以下是一個建立字串列表的示例。然後使用 len() 方法返回列表的長度

# finding the length of the list
li = ["Python","Java","CSS","Javascript"]
# Returning the length of the list
print("The length of the given list is:", len(li))

以上程式碼的輸出如下

The length of the given list is: 4

示例

在下面給出的示例中,建立了一個元素陣列。然後使用 len() 方法返回陣列的大小

# finding the length of the array
array = ["Jyoti","Radhika","Kriti","Suhana","Akriti","Ankita","Nachiket"]
# Returning the length of the list
print("The length of the given array is:", len(array))

執行以上程式碼後,我們得到以下輸出

The length of the given array is: 7

示例

在下面的示例中,建立一個字典並返回字典的長度

# finding the length of the dictionary
dictionary = {'Player': 'Sachin Tendulkar', 'Sports':'Cricket', 'age':48}
res = len(dictionary)
# Returning the length of the list
print("The length of the given array is:", res)

執行以上程式時,會產生以下結果

The length of the given array is: 3
python_strings.htm
廣告