掌握多种
Python技能对于我们更好、更灵活地应用python非常重要。比如,要得到我接下来要介绍给你的字节长度,你心里应该有个印象。有多少种方法?一起来看看吧~
1、
使用len()函数
这是最直接的方法。
在这里,我们使用
len()函数。 字符串作为参数传递给函数,我们就能得到字符串的长度。
下面,我们通过一个实例来演示一下:
str ="Tutorials"
print("Length of the String is:", len(str))
输出:
Length of the String is: 9
2、使用切片
我们可以使用字符串切片的方法来计算每个字符在字符串中的位置。
字符串中位数的最终计数成为字符串的长度。
示例如下:
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
3、使用join()和count()方法
我们也可以使用
join()和count()方法来获得字符串长度,示例如下:
str = "Tutorials"
#iterate through each character of the string
# and count them
length=((str).join(str)).count(str) + 1
# Print the total number of positions
print("The total number of characters in the string: ",length)
输出:
The total number of characters in the string: 9
以上是三种读取字符串长度的方法。
~
如需了解更多
python实用知识,点击进入
。
本文为原创文章,版权归知行编程网所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ 什么是python图像处理09/26
- ♥ python中如何使用XPath爬取小说12/15
- ♥ python读取txt乱码的解决方法11/24
- ♥ 如何用 Python 表达力量11/04
- ♥ python 元组是如何打包和解包的11/17
- ♥ 如何用python编写游戏12/30
内容反馈