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)