网站首页 > 技术文章 正文
在这一节中,我们将介绍3种方法来实现查找字符串长度.
使用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"
#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
好!上面三种方法输出结果相同!
我们可以看到,第一种方法是最简洁的!
你学会了吗?
欢迎大家留言,一起讨论学习,
谢谢关注!
猜你喜欢
- 2024-11-20 Python基础编程——算术运算
- 2024-11-20 Python字符串方法之-字符串填充
- 2024-11-20 Python第14题:最长公共前缀【leetcode】
- 2024-11-20 从 0 到 1:构建强大且易用的规则引擎
- 2024-11-20 分享3个干货满满的Python实战项目,点赞收藏
- 2024-11-20 python笔记8:静静一起来学习-字符串相关方法
- 2024-11-20 零基础Python完全自学教程14:Python中的序列知识详解
- 2024-11-20 你需要了解的最重要的Python概念
- 2024-11-20 Python整数缓存机制
- 2024-11-20 老鸟进阶必备技能,看懂显示器参数
- 02-21走进git时代, 你该怎么玩?_gits
- 02-21GitHub是什么?它可不仅仅是云中的Git版本控制器
- 02-21Git常用操作总结_git基本用法
- 02-21为什么互联网巨头使用Git而放弃SVN?(含核心命令与原理)
- 02-21Git 高级用法,喜欢就拿去用_git基本用法
- 02-21Git常用命令和Git团队使用规范指南
- 02-21总结几个常用的Git命令的使用方法
- 02-21Git工作原理和常用指令_git原理详解
- 最近发表
- 标签列表
-
- cmd/c (57)
- c++中::是什么意思 (57)
- sqlset (59)
- ps可以打开pdf格式吗 (58)
- phprequire_once (61)
- localstorage.removeitem (74)
- routermode (59)
- vector线程安全吗 (70)
- & (66)
- java (73)
- org.redisson (64)
- log.warn (60)
- cannotinstantiatethetype (62)
- js数组插入 (83)
- resttemplateokhttp (59)
- gormwherein (64)
- linux删除一个文件夹 (65)
- mac安装java (72)
- reader.onload (61)
- outofmemoryerror是什么意思 (64)
- flask文件上传 (63)
- eacces (67)
- 查看mysql是否启动 (70)
- java是值传递还是引用传递 (58)
- 无效的列索引 (74)