python中如何获取字符串长度_字符串长度怎么自己数

python中如何获取字符串长度_字符串长度怎么自己数Weprogrammersgenerallyusestringdatainourapplications.Whileusingthestringdataoneofthemostusedopera

We programmers generally use string data in our applications. While using the string data one of the most used operation is getting the size or length of the string. In this tutorial we will look different methods to get the length of the string.

我们的程序员通常在我们的应用程序中使用字符串数据。 使用字符串数据时,最常用的一种操作是获取字符串的大小或长度。 在本教程中,我们将寻找不同的方法来获取字符串的长度。

使用镜头功能 (Using Len Function)

Python have build in function named len which will provide the length of the given string. We will just provide the string variable name or string directly to the len function like below.

Python具有名为len内置函数,该函数将提供给定字符串的长度。 我们只将字符串变量名或字符串直接提供给len函数,如下所示。

myname="poftut.com" 
len(myname) 
#10 
len("poftut.com") 
#10
Using Len Function
Using Len Function
使用镜头功能

使用SizeOf函数(Using SizeOf Function)

Another way to get the length of a string is using sys library provided sizeof function. sizeof actually provide the size as byte.

获取字符串长度的另一种方法是使用sys库提供的sizeof函数。 sizeof实际上以字节为单位提供大小。

import sys         
sys.getsizeof(myname) 
#59 
sys.getsizeof("poftut.com") 
#59
Using SizeOf Function
Using SizeOf Function
使用SizeOf函数

用For计数(Counting with For)

Another and last way is counting the given string by using while or for iterations by ourself. As we know strings are just a list of characters so we can iterate over these characters. While iterating we can count the characters. This type of count operation provides some flexibility like skipping some characters and do not add total count. We will use following for loop.

另一种也是最后一种方法是通过使用while或自己for迭代来计数给定的字符串。 我们知道字符串只是字符列表,因此我们可以遍历这些字符。 在迭代时,我们可以计算字符数。 这种类型的计数操作提供了一些灵活性,例如跳过某些字符并且不增加总计数。 我们将使用以下for循环。

count=0 
for ch in myname:  
   count=count+1 
 
print(count) 
#10
Counting with For
Counting with For
用For计数

We can create a simple function like below.

我们可以创建一个简单的函数,如下所示。

def strcount(mystr): 
   count=0           
   for ch in mystr:  
      count=count+1  
   return count      
 
strcount(myname) 
10
Counting with For
Counting with For
用For计数

LEARN MORE  Php – Operators

了解更多信息-运营商

翻译自: https://www.poftut.com/get-python-string-length/

今天的文章python中如何获取字符串长度_字符串长度怎么自己数分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:http://bianchenghao.cn/71559.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注