在 Python 中查找字符串的长度(3 种方法)
pythonserver side programmingprogramming更新于 2025/9/22 11:24:17
字符串是 Python 中的一系列 Unicode 字符。一旦声明,它就不可更改。在本文中,我们将了解查找字符串长度的不同方法。
使用 len()
这是最直接的方法。这里我们使用一个名为 len() 的库函数。字符串作为参数传递给函数,我们会得到屏幕上的字符数。
示例
str ="Tutorials"
print("Length of the String is:", len(str))
输出
运行上述代码得到以下结果 −
Length of the String is: 9
使用切片
我们可以使用字符串切片方法来计算字符串中每个字符的位置。字符串中位置数量的最终计数将成为字符串的长度。
示例
str = "Tutorials"
position = 0
# 当所有位置都计数完毕后停止
while str[position:]:
position += 1
# 打印位置总数
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"
# 遍历字符串的每个字符
# 并计数
length=((str).join(str)).count(str) + 1
# 打印位置总数
print("The total number of characters in the string: ",length)
输出
运行上述代码得到以下结果 −
The total number of characters in the string: 9
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

