在python中查找字符串的长度(3种方式)
String是一个python,它是一系列Unicode字符。声明后即不可更改。在本文中,我们将介绍查找字符串长度的不同方法。
使用len()
这是最直接的方法。在这里,我们使用名为的库函数len()。字符串作为参数传递给函数,我们在屏幕上获得了字符数。
例子
str ="Tutorials"
print("字符串的长度是:", len(str))输出结果
运行上面的代码给我们以下结果-
字符串的长度是: 9
使用切片
我们可以使用字符串切片方法来计算字符串中每个字符的位置。字符串中位数的最终计数成为字符串的长度。
例子
str = "Tutorials"
position = 0
# Stop when all the positions are counted
while str[position:]:
position += 1
# Print the total number of positions
print("The total number of characters in the string: ",position)输出结果
运行上面的代码给我们以下结果-
The total number of characters in the string: 9
使用join()和count()
的join()和count()字符串函数也可以使用
例子
str = "Tutorials"
#iterate through each character of the string
# and count them
length=((str).join(str)).count(str) + 1
# Print the total number of positions
print("The total number of characters in the string: ",length)输出结果
运行上面的代码给我们以下结果-
The total number of characters in the string: 9
热门推荐
10 病人祝福语老师寄语简短
11 新娘生孩子祝福语简短
12 婆婆66岁祝福语简短
13 今天孩子高考祝福语简短
14 送彩票生日祝福语简短
15 分别祝福语简短情话英文
16 画室揭牌仪式祝福语简短
17 女友妈妈生日祝福语简短
18 离别赠言离职祝福语简短