Python三種計算字符串長度的函數(shù)
1、使用內(nèi)置函數(shù)len
這是Python中一種常用的函數(shù),主要功能就是對字符串的長度進(jìn)行統(tǒng)計,最后會返回一個字符串的實(shí)際長度,使用方法如下:
str = "hello python"
print(len(str))
在示例中str就是一個要計算的字符串,它還可以是列表或者是字典等等。
2、使用for循環(huán)
使用for循環(huán)來統(tǒng)計字符串的長度時,我們可以將for循環(huán)中的迭代次數(shù)進(jìn)行統(tǒng)計,最后再輸出字符串的長度。例如:
# 返回字符串長度文章來源:http://www.zghlxwxcb.cn/news/detail-539731.html
# 使用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)和切片
使用這個方法是第一步就是對字符串進(jìn)行切片的操作,如何在之后的每一次迭代中都縮短1,最終產(chǎn)生一個空字符,當(dāng)空字符串產(chǎn)生之后while循環(huán)也停止了。最后保持迭代次數(shù)的計算,最后輸出字符串的長度。例如:文章來源地址http://www.zghlxwxcb.cn/news/detail-539731.html
# 使用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ù)
# 使用內(nèi)置函數(shù)len
str = "hello python"
print(len(str))
代碼運(yùn)行結(jié)果
C:\軟件\python-jupyter\python.exe "F:/Big data Project/demo01/練習(xí)代碼/return使用和計算字符串長度.py"
11
7
8
12
進(jìn)程已結(jié)束,退出代碼0
到了這里,關(guān)于Python計算字符串長度的函數(shù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!