如何在 Python 中获取字符串的长度?


字符串是一组字符,可以用来表示单个单词或整个短语。在 Python 中,字符串易于使用,因为它们不需要显式声明,并且可以使用或不使用说明符来定义。

Python 有多种内置函数和方法用于操作和访问字符串。因为 Python 中的一切都是对象,所以字符串是 String 类的一个对象,它有几种方法。

在这篇文章中,我们将讨论如何在 Python 中获取字符串的长度。

使用 len() 函数

Python 中的len()函数接受字符串作为参数并返回其长度。此函数不仅可以用于字符串,还可以用于列表或任何可迭代对象。

示例

在下面给出的程序中,我们正在获取一个字符串作为输入,并使用 len() 函数找出该字符串的长度。

s1 = "Tutorialspoint" length = len(s1) print("The Length of the string",s1,"is",length)

输出

上述程序的输出为:

('The Length of the string', 'Tutorialspoint', 'is', 14)

使用切片运算符

我们还可以使用切片运算符计算字符串的长度。我们可以使用切片运算符遍历字符串,并在出现字符的每个位置将计数增加一个值。计数的最终值将是字符串的长度。

示例

在下面给出的程序中,我们正在使用获取字符串输入,并且我们正在使用切片运算符获取一个可迭代变量来遍历字符串并找到字符串的长度。

s1 = "Tutorialspoint" i = 0 while s1[i:]: i += 1 print("The length of the string",s1,"is",i)

输出

上述程序的输出为:

('The length of the string', 'Tutorialspoint', 'is', 14)

使用 for in 循环

我们可以使用循环遍历字符串并计算其中的字符数。

示例

以下是一个示例:

s1 = "Tutorialspoint" i = 0 for char in s1: i += 1 print("The length of the string",s1,"is",i)

输出

上述程序的输出为:

('The length of the string', 'Tutorialspoint', 'is', 14)

使用 join() 和 count() 方法

join 函数返回一个可迭代对象作为输出,因此通过使用 count() 方法,我们可以找到结果可迭代对象中的字符数。

示例

在下面给出的示例中,我们使用 join() 和 count() 方法来找出可迭代对象的数目并使用 count() 对其进行计数。

s1 = "Tutorialspoint" length=((s1).join(s1)).count(s1) + 1 print("The length of the string",s1,"is",length)

输出

上述程序的输出为:

('The length of the string', 'Tutorialspoint', 'is', 14)

更新于:2022年10月19日

3K+ 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.