如何在Python中获取字符串的长度?
字符串是一组字符,可以用来表示一个单词或整个短语。在Python中,字符串很容易使用,因为它们不需要显式声明,并且可以带有或不带有指定符号的定义。
Python具有各种内置函数和方法,用于操作和访问字符串。因为Python中的一切都是对象,所以字符串是String类的一个对象,它有几种方法。
在本文中,我们将讨论如何在Python中获取字符串的长度。
阅读更多:Python 教程
使用len()函数
len() 函数在Python中接受一个字符串作为参数并返回其长度。这个函数不仅可以用于字符串,还可以用于列表或任何可迭代的对象。
示例
在下面的程序中,我们输入一个字符串,并使用len()函数找出该字符串的长度。
s1 = "Tutorialspoint"
length = len(s1)
print("The Length of the string", s1, "is", length)
输出
以上程序的输出为:
('The Length of the string', 'Tutorialspoint', 'is', 14)
使用slice操作符
我们也可以使用slice操作符来计算字符串的长度。我们可以使用slice操作符遍历字符串,在每个出现字符的位置累加计数。计数的最终值将是字符串的长度。
示例
在下面的程序中,我们输入一个字符串,并使用slice操作符遍历该字符串并找到它的长度。
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循环
我们可以使用循环遍历字符串并计算其中字符的数量。
示例
下面是一个示例:
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("该字符串的长度为",s1,"为",length)
输出
上述程序的输出为,
('该字符串的长度为', 'Tutorialspoint', '为', 14)
极客教程