在python中确定字符串的长度_在python中查找字符串的长度(3种方式)

String是一个python,它是一系列Unicode字符。声明后即不可更改。在本文中,我们将介绍查找字符串长度的不同方法。

使用 len()

这是最直接的方法。在这里,我们使用名为的库函数len()。字符串作为参数传递给函数,我们在屏幕上获得了字符数。

例子str ="Tutorials"

print("字符串的长度是:", len(str))

输出结果

运行上面的代码给我们以下结果-字符串的长度是: 9

使用切片

我们可以使用字符串切片方法来计算字符串中每个字符的位置。字符串中位数的最终计数成为字符串的长度。

例子str = "Tutorials"

position = 0

# Stop when all the positions are counted

while str[position:]:

position += 1

# Print the total number of positions

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

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值