python string length_如何使用python获取字符串长度?哪些方法?
掌握多種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實用知識,點擊進入JQ教程網Python大全。
總結
以上是生活随笔為你收集整理的python string length_如何使用python获取字符串长度?哪些方法?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 隆力奇护手霜Logo撞脸Python 网
- 下一篇: python中线程和进程_python中