Python三种计算字符串长度的函数
1、使用内置函数len
这是Python中一种常用的函数,主要功能就是对字符串的长度进行统计,最后会返回一个字符串的实际长度,使用方法如下:
1
2
str
=
"hello python"
print
(
len
(
str
))
在示例中str就是一个要计算的字符串,它还可以是列表或者是字典等等。
2、使用for循环
使用for循环来统计字符串的长度时,我们可以将for循环中的迭代次数进行统计,最后再输出字符串的长度。例如:
# 返回字符串长度
1
2
3
4
5
6
7
8
9
# 使用for循环(方法一)
def
my_len():
s1
=
"hello world"
length
=
0
for
i
in
s1:
length
=
length
+
1
return
length
# 函数的返回值
pass
1
2
3
4
5
6
7
# 使用for循环(方法二)
def
HH(
str
):
count
=
0
for
i
in
str
:
count
+
=
1
return
count
pass
3、使用while循环和切片
使用这个方法是第一步就是对字符串进行切片的操作,如何在之后的每一次迭代中都缩短1,最终产生一个空字符,当空字符串产生之后while循环也停止了。最后保持迭代次数的计算,最后输出字符串的长度。例如:
1
2
3
4
5
6
7
# 使用while循环和切片
def
ww(
str
):
count
=
0
while
str
[count:]:
count
+
=
1
return
count
pass
代码
代码展示
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Python计算字符串长度的函数
# 使用for循环(方法一)
def
my_len():
s1
=
"hello world"
length
=
0
for
i
in
s1:
length
=
length
+
1
return
length
# 函数的返回值
pass
# 使用for循环(方法二)
def
HH(
str
):
count
=
0
for
i
in
str
:
count
+
=
1
return
count
pass
# 使用while循环和切片
def
ww(
str
):
count
=
0
while
str
[count:]:
count
+
=
1
return
count
pass
def
main():
# 使用for循环,方法一
str_len
=
my_len()
print
(str_len)
# 使用for循环,方法二
str1
=
"hello !"
print
(HH(str1))
# 使用while循环
str2
=
"while 循环"
print
(ww(str2))
pass
if
__name__
=
=
'__main__'
:
main()
# Python计算字符串长度的函数
# 使用内置函数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求字符串的长度的文章就介绍到这了,希望可以帮到你。
转自:微点阅读 https://www.weidianyuedu.com