python学习




在这一节中,我们将介绍3种方法来实现查找字符串长度.


使用len()函数

这是最直接的方法。 在这里,我们使用len()函数。 字符串作为参数传递给函数,我们就能得到字符串的长度。


下面,我们通过一个实例来演示一下:

str ="Tutorials"print("Length of the String is:", len(str))

输出:

Length of the String is: 9

使用切片

我们可以使用字符串切片方法来计算字符串中每个字符的位置。 字符串中位数的最终计数成为字符串的长度。

示例如下:

str = "Tutorials"position = 0while str[position:]:   position += 1print("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 themlength=((str).join(str)).count(str) + 1# Print the total number of positionsprint("The total number of characters in the string: ",length)

输出:

The total number of characters in the string: 9

好!上面三种方法输出结果相同!

我们可以看到,第一种方法是最简洁的!


你学会了吗?

欢迎大家留言,一起讨论学习,

谢谢关注!