Python求字符串的長度示例代碼
Python求字符串的長度
python 寫一個函數(shù),求一個字符串的長度,在main函數(shù)中輸入字符串,并輸出其長度。
def func(a): #定義一個求字符串長度的函數(shù) '求一個字符串的長度' len=0 for i in a: len+=1 return len if __name__=='__main__': #main函數(shù), __name__=='__main__'將函數(shù)私有化了,外部調用不了main下面的內容。 str_input=input('請輸出一個字符串') #實現(xiàn)在main函數(shù)中輸入字符串 str_len=func(str_input) #通過調用外部的函數(shù)func(a),并傳遞實際參數(shù)str_input,實現(xiàn)在main函數(shù)計算字符串長度。 print("輸入字符串長度:", str_len) #打印字符串長度
補充:Python計算字符串長度的函數(shù)
Python三種計算字符串長度的函數(shù)
1、使用內置函數(shù)len
這是Python中一種常用的函數(shù),主要功能就是對字符串的長度進行統(tǒng)計,最后會返回一個字符串的實際長度,使用方法如下:
str = "hello python" print(len(str))
在示例中str就是一個要計算的字符串,它還可以是列表或者是字典等等。
2、使用for循環(huán)
使用for循環(huán)來統(tǒng)計字符串的長度時,我們可以將for循環(huán)中的迭代次數(shù)進行統(tǒng)計,最后再輸出字符串的長度。例如:
# 返回字符串長度
# 使用for循環(huán)(方法一) def my_len(): s1 = "hello world" length = 0 for i in s1: length = length + 1 return length # 函數(shù)的返回值 pass
# 使用for循環(huán)(方法二) def HH(str): count = 0 for i in str: count += 1 return count pass
3、使用while循環(huán)和切片
使用這個方法是第一步就是對字符串進行切片的操作,如何在之后的每一次迭代中都縮短1,最終產生一個空字符,當空字符串產生之后while循環(huán)也停止了。最后保持迭代次數(shù)的計算,最后輸出字符串的長度。例如:
# 使用while循環(huán)和切片 def ww(str): count = 0 while str[count:]: count += 1 return count pass
代碼
代碼展示
# Python計算字符串長度的函數(shù) # 使用for循環(huán)(方法一) def my_len(): s1 = "hello world" length = 0 for i in s1: length = length + 1 return length # 函數(shù)的返回值 pass # 使用for循環(huán)(方法二) def HH(str): count = 0 for i in str: count += 1 return count pass # 使用while循環(huán)和切片 def ww(str): count = 0 while str[count:]: count += 1 return count pass def main(): # 使用for循環(huán),方法一 str_len = my_len() print(str_len) # 使用for循環(huán),方法二 str1 = "hello !" print(HH(str1)) # 使用while循環(huán) str2 = "while 循環(huán)" print(ww(str2)) pass if __name__ == '__main__': main() # Python計算字符串長度的函數(shù) # 使用內置函數(shù)len str = "hello python" print(len(str))
代碼運行結果
C:\軟件\python-jupyter\python.exe "F:/Big data Project/demo01/練習代碼/return使用和計算字符串長度.py"
11
7
8
12進程已結束,退出代碼0
到此這篇關于Python求字符串的長度的文章就介紹到這了,更多相關Python求字符串長度內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
一行代碼解決動態(tài)執(zhí)行Python函數(shù)方法實例
這篇文章主要為大家介紹了如何用一行代碼解決動態(tài)執(zhí)行Python函數(shù)方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12