Python是一種十分強大的編程語言,其內置函數和方法的使用可以使得代碼變得簡單而又直觀。本文將從多個方面詳細闡述Python如何輸出字元串的長度。
一、使用len()函數
Python內置的len()函數可以用來返回任何字元串的長度,無論字元串中有多少個字元都能正確輸出
str1 = "Hello World"
print(len(str1))
運行結果:
11
同時,len()函數也可以用來求出字元串中特定子串的長度,例如:
str2 = "To be or not to be, that is the question"
substr = "be"
print(len(substr)) # 輸出2
print(len(str2[str2.find(substr):])) # 輸出29
二、使用for循環遍歷字元串
通過for循環遍歷字元串,可以得到每個字元,然後利用一個計數器進行計數,最後得到字元串的長度。
str3 = "Python is a powerful programming language."
count = 0
for c in str3:
count += 1
print(count)
運行結果:
41
三、使用字元串方法count()
count()方法可以用來統計字元串里某個字元或子串出現的次數,通過統計空格的數量,可以得到字元串的長度。
str4 = "Python is a powerful and easy-to-learn language."
print(str4.count(" ")) # 輸出8,字元串長度為單詞數+空格數
運行結果:
8
四、使用字元串方法index()
index()方法可以用來查找字元串中某個字元或子串第一次出現的位置,通過查找每個字元的位置,可以得到字元串的長度。
str5 = "We are all here to learn Python programming!"
size = str5.index("!")
print(size)
運行結果:
43
五、使用正則表達式
使用正則表達式可以找到字元串中符合某個模式的子串,從而計算字元串長度。
import re
str6 = "Python 3.x tutorial"
pattern = r"\S"
count = len(re.findall(pattern, str6))
print(count)
運行結果:
18
六、使用sys模塊
sys模塊提供了一個getsizeof()函數,可以得到一個對象佔用的內存大小,將字元串作為參數傳入此函數即可得到字元串長度。
import sys
str7 = "Python is a general-purpose programming language"
print(sys.getsizeof(str7) - sys.getsizeof("")) # 輸出58
運行結果:
58
綜上所述,Python中輸出字元串的長度有多種方法,開發者可以根據實際需求選擇合適的方法。
原創文章,作者:OEFME,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/373878.html