網站首頁 編程語言 正文
Python求字符串的長度
?python 寫一個函數,求一個字符串的長度,在main函數中輸入字符串,并輸出其長度。
def func(a): #定義一個求字符串長度的函數
'求一個字符串的長度'
len=0
for i in a:
len+=1
return len
if __name__=='__main__': #main函數, __name__=='__main__'將函數私有化了,外部調用不了main下面的內容。
str_input=input('請輸出一個字符串') #實現在main函數中輸入字符串
str_len=func(str_input) #通過調用外部的函數func(a),并傳遞實際參數str_input,實現在main函數計算字符串長度。
print("輸入字符串長度:", str_len) #打印字符串長度
補充:Python計算字符串長度的函數
Python三種計算字符串長度的函數
1、使用內置函數len
這是Python中一種常用的函數,主要功能就是對字符串的長度進行統計,最后會返回一個字符串的實際長度,使用方法如下:
str = "hello python"
print(len(str))
在示例中str就是一個要計算的字符串,它還可以是列表或者是字典等等。
2、使用for循環
使用for循環來統計字符串的長度時,我們可以將for循環中的迭代次數進行統計,最后再輸出字符串的長度。例如:
# 返回字符串長度
# 使用for循環(方法一)
def my_len():
s1 = "hello world"
length = 0
for i in s1:
length = length + 1
return length
# 函數的返回值
pass
# 使用for循環(方法二)
def HH(str):
count = 0
for i in str:
count += 1
return count
pass
3、使用while循環和切片
使用這個方法是第一步就是對字符串進行切片的操作,如何在之后的每一次迭代中都縮短1,最終產生一個空字符,當空字符串產生之后while循環也停止了。最后保持迭代次數的計算,最后輸出字符串的長度。例如:
# 使用while循環和切片
def ww(str):
count = 0
while str[count:]:
count += 1
return count
pass
代碼
代碼展示
# Python計算字符串長度的函數
# 使用for循環(方法一)
def my_len():
s1 = "hello world"
length = 0
for i in s1:
length = length + 1
return length
# 函數的返回值
pass
# 使用for循環(方法二)
def HH(str):
count = 0
for i in str:
count += 1
return count
pass
# 使用while循環和切片
def ww(str):
count = 0
while str[count:]:
count += 1
return count
pass
def main():
# 使用for循環,方法一
str_len = my_len()
print(str_len)
# 使用for循環,方法二
str1 = "hello !"
print(HH(str1))
# 使用while循環
str2 = "while 循環"
print(ww(str2))
pass
if __name__ == '__main__':
main()
# Python計算字符串長度的函數
# 使用內置函數len
str = "hello python"
print(len(str))
代碼運行結果
C:\軟件\python-jupyter\python.exe "F:/Big data Project/demo01/練習代碼/return使用和計算字符串長度.py"
11
7
8
12進程已結束,退出代碼0
原文鏈接:https://jn10010537.blog.csdn.net/article/details/80307648
相關推薦
- 2023-11-15 Python pip指定安裝鏡像源;pip安裝如何指定和更改鏡像源?
- 2022-03-28 C#委托方法Func()中GetInvocationList()方法的用法介紹_基礎應用
- 2024-03-03 layuiadmin新建tabs標簽頁,點擊保存,打開新的標簽頁并刷新
- 2022-08-18 Android顏色處理SweepGradient掃描及梯度渲染示例_Android
- 2022-05-11 RabbitMq工作模式深度剖析與Spring整合MQ
- 2023-06-05 關于C++的.cpp文件運行全過程_C 語言
- 2022-07-23 asp.net6?blazor?文件上傳功能_實用技巧
- 2022-05-20 python?列表常用方法超詳細梳理總結_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支